mysql_db.py 4.6 KB

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