mysql_db.py 4.3 KB

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