__init__.py 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  1. """
  2. @author: luojunhui
  3. """
  4. import pymysql
  5. from contextlib import contextmanager
  6. from .exceptions import QueryError, TransactionError
  7. class DatabaseConnector:
  8. """
  9. 数据库连接器,使用 pymysql 进行 MySQL 数据库操作。
  10. """
  11. def __init__(self, db_config):
  12. """
  13. 初始化数据库连接配置。
  14. :param db_config:
  15. """
  16. self.db_config = db_config
  17. self.connection = None
  18. def connect(self):
  19. """
  20. 建立数据库连接。
  21. :raises ConnectionError: 如果无法连接到数据库。
  22. """
  23. try:
  24. self.connection = pymysql.connect(
  25. host=self.db_config.get('host', 'localhost'),
  26. user=self.db_config['user'],
  27. password=self.db_config['password'],
  28. db=self.db_config['db'],
  29. port=self.db_config.get('port', 3306),
  30. charset=self.db_config.get('charset', 'utf8mb4')
  31. )
  32. except pymysql.MySQLError as e:
  33. raise ConnectionError(f"无法连接到数据库: {e}")
  34. def close(self):
  35. """
  36. 关闭数据库连接。
  37. """
  38. if self.connection:
  39. self.connection.close()
  40. self.connection = None
  41. def execute_query(self, query, params=None):
  42. """
  43. 执行单条查询语句,并返回结果。
  44. :param query: SQL 查询语句。
  45. :param params: 可选的参数,用于参数化查询。
  46. :return: 查询结果列表。
  47. :raises QueryError: 如果执行查询时出错。
  48. """
  49. if not self.connection:
  50. self.connect()
  51. try:
  52. with self.connection.cursor() as cursor:
  53. cursor.execute(query, params)
  54. result = cursor.fetchall()
  55. return result
  56. except pymysql.MySQLError as e:
  57. self.connection.rollback()
  58. raise QueryError(f"查询执行失败: {e}")
  59. def execute_many(self, query, params_list):
  60. """
  61. 执行多条查询语句。
  62. :param query: SQL 查询语句。
  63. :param params_list: 包含多个参数的列表。
  64. :raises QueryError: 如果执行查询时出错。
  65. """
  66. if not self.connection:
  67. self.connect()
  68. try:
  69. with self.connection.cursor() as cursor:
  70. cursor.executemany(query, params_list)
  71. except pymysql.MySQLError as e:
  72. self.connection.rollback()
  73. raise QueryError(f"批量查询执行失败: {e}")
  74. def commit(self):
  75. """
  76. 提交当前事务。
  77. :raises TransactionError: 如果提交事务时出错。
  78. """
  79. if not self.connection:
  80. raise TransactionError("没有活动的数据库连接。")
  81. try:
  82. self.connection.commit()
  83. print("事务提交成功。")
  84. except pymysql.MySQLError as e:
  85. self.connection.rollback()
  86. raise TransactionError(f"提交事务失败: {e}")
  87. def rollback(self):
  88. """
  89. 回滚当前事务。
  90. :raises TransactionError: 如果回滚事务时出错。
  91. """
  92. if not self.connection:
  93. raise TransactionError("没有活动的数据库连接。")
  94. try:
  95. self.connection.rollback()
  96. print("事务已回滚。")
  97. except pymysql.MySQLError as e:
  98. raise TransactionError(f"回滚事务失败: {e}")
  99. @contextmanager
  100. def transaction(self):
  101. """
  102. 上下文管理器,用于处理事务。
  103. 使用示例:
  104. with db.transaction():
  105. db.execute_query("INSERT INTO ...")
  106. db.execute_query("UPDATE ...")
  107. """
  108. try:
  109. yield
  110. self.commit()
  111. except Exception as e:
  112. self.rollback()
  113. raise e
  114. def __enter__(self):
  115. """
  116. 支持 with 语句,进入上下文时建立连接。
  117. """
  118. self.connect()
  119. return self
  120. def __exit__(self, exc_type, exc_val, exc_tb):
  121. """
  122. 支持 with 语句,退出上下文时关闭连接。
  123. """
  124. if exc_type:
  125. self.rollback()
  126. self.close()