DBDownload.py 2.8 KB

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