operate_mysql.py 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import pymysql
  2. import traceback
  3. import time
  4. import datetime
  5. from configuration import Configuration
  6. from AES_crypt import decrypt
  7. class OperateMysql():
  8. config = Configuration().get_config()
  9. config = config["hardDiskdataBase"]
  10. def __init__(self, config=config, port=3306, charset='utf8'):
  11. self.host = config['ip']
  12. self.user = config['username']
  13. self.passwd = decrypt(config['password'])
  14. self.db = config['dataBaseName']
  15. self.port = port
  16. self.charset = charset
  17. self.conn = None
  18. self._conn()
  19. def _conn(self):
  20. try:
  21. self.conn = pymysql.connect(host=self.host, user=self.user, password=self.passwd, db=self.db, port=self.port, autocommit=True)
  22. return True
  23. except Exception as e:
  24. print(e)
  25. return False
  26. def _reConn(self, num=28800, stime=3): # 重试连接总次数为1天,这里根据实际情况自己设置,如果服务器宕机1天都没发现就......
  27. _number = 0
  28. _status = True
  29. while _status and _number <= num:
  30. try:
  31. self.conn.ping() # cping 校验连接是否异常
  32. _status = False
  33. except:
  34. if self._conn() == True: # 重新连接,成功退出
  35. _status = False
  36. break
  37. _number += 1
  38. time.sleep(stime) # 连接不成功,休眠3秒钟,继续循环,知道成功或重试次数结束
  39. def execute_sql(self, sql):
  40. try:
  41. self._reConn()
  42. self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor)
  43. self.cursor.execute(sql)
  44. results = self.cursor.fetchall()
  45. self.cursor.close()
  46. return results
  47. except:
  48. print(traceback.format_exc())
  49. return None
  50. def return_result(self, point_statistic, serial_number):
  51. # "parameter":{"key": "s2", "basic_data": "c2", "begin_time": "1618389390", "end_time": "1618389572"}
  52. begin_time = datetime.datetime.fromtimestamp(int(point_statistic['begin_time']))
  53. end_time = datetime.datetime.fromtimestamp(int(point_statistic['end_time']))
  54. sql = "SELECT device_name FROM data_point_tbl WHERE serial_number=%s;" % (serial_number)
  55. res = self.execute_sql(sql)
  56. table_name = 'table_' + res[0]['device_name']
  57. dict_res = {"table_name": table_name, "begin_time": begin_time, "end_time": end_time}
  58. return dict_res
  59. # def database_parameters(self):
  60. # config = {'ip': 'localhost', 'username': 'rootroot', 'password': 'rootroot', 'dataBaseName': 'shucai'}
  61. # self.config = config