DBDownload.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import pymysql
  2. import time
  3. import pandas as pd
  4. class DBDownload:
  5. def __init__(self, host='', port='', db='', user='', password=''):
  6. self.host = host
  7. self.port = port
  8. self.db = db
  9. self.user = user
  10. self.password = password
  11. pass
  12. def __enter__(self):
  13. self.connect()
  14. return self
  15. def __exit__(self, exc_type, exc_val, exc_tb):
  16. self.close()
  17. def connect(self):
  18. conn_success_flag = 0
  19. while not conn_success_flag:
  20. try:
  21. self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, database=self.db)
  22. except Exception as e:
  23. conn_success_flag = 0
  24. print("数据库连接失败 :{}".format(e))
  25. time.sleep(5)
  26. else:
  27. conn_success_flag = 1
  28. print('数据库连接成功!')
  29. self.cursor = self.conn.cursor()
  30. def getdata(self,*param,tablename,sn):
  31. print('数据获取中......')
  32. param=list(param)
  33. str=''
  34. for i in range(len(param)):
  35. if i<1:
  36. str=str+param[i]
  37. else:
  38. str=str+','+param[i]
  39. # self.cursor.execute("select %s from %s where time between '%s' and '%s'" %(str,tablename,st,sp))
  40. self.cursor.execute("select %s from %s where sn='%s' order by id desc limit 1" %(str,tablename,sn))
  41. res = self.cursor.fetchall()
  42. df_res = pd.DataFrame(res, columns=param)
  43. df_res = df_res.reset_index(drop=True)
  44. return(df_res)
  45. def close(self):
  46. try:
  47. self.cursor.close()
  48. self.conn.close()
  49. except Exception as e:
  50. print(e)
  51. else:
  52. print('数据库已断开连接!')