mysql_db.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. import pymysql
  2. import threading
  3. import traceback
  4. from conf import Config
  5. from .base_db import HGSDatabase, DBException, DBCloseException
  6. from tool.typing import *
  7. class MysqlDB(HGSDatabase):
  8. def __init__(self,
  9. host: Optional[str] = Config.mysql_url,
  10. name: Optional[str] = Config.mysql_name,
  11. passwd: Optional[str] = Config.mysql_passwd,
  12. port: Optional[str] = Config.mysql_port):
  13. if host is None or name is None:
  14. raise DBException
  15. super(MysqlDB, self).__init__(host, name, passwd, port)
  16. try:
  17. self._db = pymysql.connect(user=self._name,
  18. password=self._passwd,
  19. host=self._host,
  20. port=self._port,
  21. database="hgssystem")
  22. except pymysql.err.OperationalError:
  23. raise
  24. self._cursor = self._db.cursor()
  25. self._lock = threading.RLock()
  26. def close(self):
  27. if self._cursor is not None:
  28. self._cursor.close()
  29. if self._db is not None:
  30. self._db.close()
  31. self._db = None
  32. self._cursor = None
  33. self._lock = None
  34. def is_connect(self) -> bool:
  35. if self._cursor is None or self._db is None:
  36. return False
  37. return True
  38. def get_cursor(self) -> pymysql.cursors.Cursor:
  39. if self._cursor is None or self._db is None:
  40. raise DBCloseException
  41. return self._cursor
  42. def search(self, columns: List[str], table: str,
  43. where: Union[str, List[str]] = None,
  44. limit: Optional[int] = None,
  45. offset: Optional[int] = None,
  46. order_by: Optional[List[Tuple[str, str]]] = None,
  47. group_by: Optional[List[str]] = None):
  48. if type(where) is list and len(where) > 0:
  49. where: str = " WHERE " + " AND ".join(f"({w})" for w in where)
  50. elif type(where) is str and len(where) > 0:
  51. where = " WHERE " + where
  52. else:
  53. where: str = ""
  54. if order_by is None:
  55. order_by: str = ""
  56. else:
  57. by = [f" {i[0]} {i[1]} " for i in order_by]
  58. order_by: str = " ORDER BY" + ", ".join(by)
  59. if limit is None or limit == 0:
  60. limit: str = ""
  61. else:
  62. limit = f" LIMIT {limit}"
  63. if offset is None:
  64. offset: str = ""
  65. else:
  66. offset = f" OFFSET {offset}"
  67. if group_by is None:
  68. group_by: str = ""
  69. else:
  70. group_by = "GROUP BY " + ", ".join(group_by)
  71. columns: str = ", ".join(columns)
  72. return self.__search(f"SELECT {columns} FROM {table} {where} {group_by} {order_by} {limit} {offset};")
  73. def insert(self, table: str, columns: list, values: Union[str, List[str]], not_commit: bool = False):
  74. columns: str = ", ".join(columns)
  75. if type(values) is str:
  76. values: str = f"({values})"
  77. else:
  78. values: str = ", ".join(f"{v}" for v in values)
  79. return self.__done(f"INSERT INTO {table}({columns}) VALUES {values};", not_commit=not_commit)
  80. def delete(self, table: str, where: Union[str, List[str]] = None, not_commit: bool = False):
  81. if type(where) is list and len(where) > 0:
  82. where: str = " AND ".join(f"({w})" for w in where)
  83. elif type(where) is not str or len(where) == 0: # 必须指定条件
  84. return None
  85. return self.__done(f"DELETE FROM {table} WHERE {where};", not_commit=not_commit)
  86. def update(self, table: str, kw: dict[str:str], where: Union[str, List[str]] = None, not_commit: bool = False):
  87. if len(kw) == 0:
  88. return None
  89. if type(where) is list and len(where) > 0:
  90. where: str = " AND ".join(f"({w})" for w in where)
  91. elif type(where) is not str or len(where) == 0: # 必须指定条件
  92. return None
  93. kw_list = [f"{key} = {kw[key]}" for key in kw]
  94. kw_str = ", ".join(kw_list)
  95. return self.__done(f"UPDATE {table} SET {kw_str} WHERE {where};", not_commit=not_commit)
  96. def __search(self, sql) -> Union[None, pymysql.cursors.Cursor]:
  97. if self._cursor is None or self._db is None:
  98. raise DBCloseException
  99. try:
  100. self._lock.acquire() # 上锁
  101. self._cursor.execute(sql)
  102. except pymysql.MySQLError:
  103. print(f"{sql}")
  104. traceback.print_exc()
  105. return None
  106. finally:
  107. self._lock.release() # 释放锁
  108. return self._cursor
  109. def __done(self, sql, not_commit: bool = False) -> Union[None, pymysql.cursors.Cursor]:
  110. if self._cursor is None or self._db is None:
  111. raise DBCloseException
  112. try:
  113. self._lock.acquire()
  114. self._cursor.execute(sql)
  115. except pymysql.MySQLError:
  116. self._db.rollback()
  117. print(f"{sql}")
  118. traceback.print_exc()
  119. return None
  120. finally:
  121. if not not_commit:
  122. self._db.commit()
  123. self._lock.release()
  124. return self._cursor
  125. def commit(self):
  126. try:
  127. self._lock.acquire()
  128. self._db.commit()
  129. finally:
  130. self._lock.release()