DBDownload.py 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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,factory):
  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. elif self.mode==0:
  43. self.cursor.execute("select %s from %s where sn='%s' and %s between '%s' and '%s'" %(str,tablename,sn,timename,st,sp))
  44. elif self.mode==2:
  45. self.cursor.execute("select %s from %s where factory='%s'" %(str,tablename,factory))
  46. elif self.mode==3:
  47. self.cursor.execute("select %s from %s" %(str,tablename))
  48. elif self.mode==4:
  49. self.cursor.execute("select %s from %s where qrcode='%s' order by id desc limit 1" %(str,tablename,sn))
  50. res = self.cursor.fetchall()
  51. df_res = pd.DataFrame(res, columns=param)
  52. df_res = df_res.reset_index(drop=True)
  53. return(df_res)
  54. def close(self):
  55. try:
  56. self.cursor.close()
  57. self.conn.close()
  58. except Exception as e:
  59. print(e)
  60. else:
  61. print('数据库已断开连接!')