DBDownload.py 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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. if self.mode==1:
  34. self.cursor.execute("select %s from %s where sn='%s' order by id desc limit 1" %(param,tablename,sn))
  35. else:
  36. self.cursor.execute("select %s from %s where sn='%s' and %s between '%s' and '%s'" %(param,tablename,sn,timename,st,sp))
  37. res = self.cursor.fetchall()
  38. df_res = pd.DataFrame(res, columns=param.split(','))
  39. return(df_res)
  40. def close(self):
  41. try:
  42. self.cursor.close()
  43. self.conn.close()
  44. except Exception as e:
  45. print(e)
  46. else:
  47. print('数据库已断开连接!')