__init__.py 4.8 KB

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