__init__.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  1. """
  2. @author: luojunhui
  3. """
  4. import pymysql
  5. from contextlib import contextmanager
  6. from applications.exception 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 fetch(self, query, cursor_type=None):
  42. """
  43. 执行单条查询语句,并返回结果。
  44. :param cursor_type: 输出的返回格式
  45. :param query: 查询语句
  46. :return: 查询结果列表
  47. :raises QueryError: 如果执行查询时出错。
  48. """
  49. if not self.connection:
  50. self.connect()
  51. try:
  52. with self.connection.cursor(cursor_type) as cursor:
  53. cursor.execute(query)
  54. result = cursor.fetchall()
  55. return result
  56. except pymysql.MySQLError as e:
  57. self.rollback()
  58. raise QueryError(e, query)
  59. def save(self, query, params):
  60. """
  61. 执行单条插入、更新语句
  62. :param query:
  63. :param params:
  64. :return:
  65. """
  66. if not self.connection:
  67. self.connect()
  68. try:
  69. with self.connection.cursor() as cursor:
  70. affected_rows = cursor.execute(query, params)
  71. if affected_rows:
  72. self.commit()
  73. return affected_rows
  74. else:
  75. self.rollback()
  76. return 0
  77. except pymysql.MySQLError as e:
  78. self.rollback()
  79. raise QueryError(e, query)
  80. def save_many(self, query, params_list):
  81. """
  82. 执行多条查询语句
  83. :param query: SQL 查询语句。
  84. :param params_list: 包含多个参数的列表。
  85. :raises QueryError: 如果执行查询时出错。
  86. """
  87. if not self.connection:
  88. self.connect()
  89. try:
  90. with self.connection.cursor() as cursor:
  91. affected_rows = cursor.executemany(query, params_list)
  92. if affected_rows:
  93. self.commit()
  94. return affected_rows
  95. else:
  96. self.rollback()
  97. return 0
  98. except pymysql.MySQLError as e:
  99. self.rollback()
  100. raise QueryError(e, query)
  101. def commit(self):
  102. """
  103. 提交当前事务。
  104. :raises TransactionError: 如果提交事务时出错。
  105. """
  106. if not self.connection:
  107. raise TransactionError("没有活动的数据库连接。")
  108. try:
  109. self.connection.commit()
  110. except pymysql.MySQLError as e:
  111. self.connection.rollback()
  112. raise TransactionError(f"提交事务失败: {e}")
  113. def rollback(self):
  114. """
  115. 回滚当前事务。
  116. :raises TransactionError: 如果回滚事务时出错。
  117. """
  118. if not self.connection:
  119. raise TransactionError("没有活动的数据库连接。")
  120. try:
  121. self.connection.rollback()
  122. except pymysql.MySQLError as e:
  123. raise TransactionError(f"回滚事务失败: {e}")
  124. @contextmanager
  125. def transaction(self):
  126. """
  127. 上下文管理器,用于处理事务
  128. """
  129. try:
  130. yield self.commit()
  131. except Exception as e:
  132. self.rollback()
  133. raise e
  134. def __enter__(self):
  135. """
  136. 支持 with 语句,进入上下文时建立连接。
  137. """
  138. self.connect()
  139. return self
  140. def __exit__(self, exc_type, exc_val, exc_tb):
  141. """
  142. 支持 with 语句,退出上下文时关闭连接。
  143. """
  144. if exc_type:
  145. self.rollback()
  146. self.close()