DBDownload.py 2.6 KB

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