mysql_db.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import os
  2. import mysql
  3. from mysql.connector import Error
  4. from contextlib import contextmanager
  5. class DBManager:
  6. def __init__(self):
  7. # 从环境变量获取数据库配置
  8. self.host = os.getenv('MYSQL_HOST', '100.102.238.76')
  9. self.port = int(os.getenv('MYSQL_PORT', '3307'))
  10. self.database = os.getenv('MYSQL_DATABASE', 'qinglong')
  11. self.user = os.getenv('MYSQL_USER', 'root')
  12. self.password = os.getenv('MYSQL_PASSWORD', 'root')
  13. self.connection = None
  14. def connect(self):
  15. """建立数据库连接"""
  16. try:
  17. self.connection = mysql.connector.connect(
  18. host=self.host,
  19. port=self.port,
  20. database=self.database,
  21. user=self.user,
  22. password=self.password,
  23. autocommit=False # 手动控制事务
  24. )
  25. if self.connection.is_connected():
  26. print("成功连接到MySQL数据库")
  27. except Error as e:
  28. print(f"连接数据库时出错: {e}")
  29. self.connection = None
  30. @contextmanager
  31. def managed_cursor(self):
  32. """上下文管理器,自动管理连接和游标"""
  33. try:
  34. if self.connection is None or not self.connection.is_connected():
  35. self.connect()
  36. if self.connection is None:
  37. raise Exception("数据库连接失败")
  38. cursor = self.connection.cursor()
  39. yield cursor # 在此处返回游标给调用方
  40. except Error as e:
  41. print(f"数据库操作失败: {e}")
  42. # 尝试重新连接
  43. self.connect()
  44. if self.connection and self.connection.is_connected():
  45. cursor = self.connection.cursor()
  46. yield cursor
  47. else:
  48. raise
  49. finally:
  50. try:
  51. if 'cursor' in locals() and cursor:
  52. cursor.close()
  53. except:
  54. pass # 忽略关闭游标时的异常
  55. # db_manager = DBManager()
  56. # sql = '''
  57. # select email_address, -- 邮件地址
  58. # email_password, -- 邮件密码
  59. # connection_type, -- 连接类型
  60. # receive_server_address, -- 接收邮件服务器地址
  61. # receive_server_port, -- 接收邮件服务器端口号
  62. # iyuu_token, -- 爱语飞飞token
  63. # last_check_uid -- 上次检查的UID
  64. # from check_email_config;
  65. # '''
  66. #
  67. # with db_manager.managed_cursor() as cursor:
  68. # cursor.execute(sql)
  69. # result = cursor.fetchall()
  70. # for row in result:
  71. # print(row)