mysql_helper.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. # -*- coding: utf-8 -*-
  2. # @Time : 2023/8/26
  3. # @Author : lkj
  4. # @description :
  5. import time
  6. from loguru import logger
  7. import mysql.connector
  8. class MysqlConn(object):
  9. def __init__(self,mysql_path):
  10. self.mysql_path = mysql_path
  11. self.cursor = ''
  12. self.mysql_conn = ''
  13. self.mysql_conn, self.cursor = self.link_mysql()
  14. def link_mysql(self,):
  15. """
  16. 连接
  17. """
  18. try:
  19. mysql_conn = mysql.connector.connect(
  20. host=self.mysql_path.get('mysql_host'),
  21. port=self.mysql_path.get('mysql_port'),
  22. user=self.mysql_path['mysql_user'],
  23. password=self.mysql_path['mysql_password'],
  24. database=self.mysql_path['mysql_db'],
  25. connect_timeout=6000,
  26. charset = 'utf8',
  27. )
  28. cursor = mysql_conn.cursor(buffered=True)
  29. print('mysql_course--->success')
  30. return mysql_conn, cursor
  31. except Exception as e:
  32. logger.info('连接mysql数据库失败-->{}'.format(e))
  33. return '',''
  34. def search(self, sql,data):
  35. """
  36. 查询
  37. """
  38. try:
  39. self.cursor.execute(sql,(data,))
  40. data = self.cursor.fetchall()
  41. return data, True
  42. except Exception as e:
  43. print('mysql查询错误',e)
  44. print(sql)
  45. time.sleep(5)
  46. self.mysql_conn, self.cursor = self.link_mysql()
  47. return [], False
  48. def close(self):
  49. self.cursor.close()
  50. self.mysql_conn.close()