DBDownload.py 1.9 KB

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