mysql_db.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. import pymysql
  2. import threading
  3. from conf import mysql_url, mysql_name, mysql_passwd
  4. from .base_db import Database, DBCloseException
  5. from tool.type_ import *
  6. class MysqlDB(Database):
  7. def __init__(self, host: str = mysql_url, name: str = mysql_name, passwd: str = mysql_passwd):
  8. super(MysqlDB, self).__init__(host, name, passwd)
  9. try:
  10. self._db = pymysql.connect(user=name, password=passwd, host=host, database="hgssystem")
  11. except pymysql.err.OperationalError:
  12. raise
  13. self._cursor = self._db.cursor()
  14. self._lock = threading.RLock()
  15. def close(self):
  16. if self._cursor is not None:
  17. self._cursor.close()
  18. if self._db is not None:
  19. self._db.close()
  20. self._db = None
  21. self._cursor = None
  22. self._lock = None
  23. def is_connect(self) -> bool:
  24. if self._cursor is None or self._db is None:
  25. return False
  26. return True
  27. def get_cursor(self) -> pymysql.cursors.Cursor:
  28. if self._cursor is None or self._db is None:
  29. raise DBCloseException
  30. return self._cursor
  31. def search(self, sql) -> Union[None, pymysql.cursors.Cursor]:
  32. if self._cursor is None or self._db is None:
  33. raise DBCloseException
  34. try:
  35. self._lock.acquire() # 上锁
  36. self._cursor.execute(sql)
  37. except pymysql.MySQLError:
  38. return None
  39. finally:
  40. self._lock.release() # 释放锁
  41. return self._cursor
  42. def done(self, sql) -> Union[None, pymysql.cursors.Cursor]:
  43. if self._cursor is None or self._db is None:
  44. raise DBCloseException
  45. try:
  46. self._lock.acquire()
  47. self._cursor.execute(sql)
  48. except pymysql.MySQLError:
  49. self._db.rollback()
  50. return None
  51. finally:
  52. self._db.commit()
  53. self._lock.release()
  54. return self._cursor
  55. def done_(self, sql) -> Union[None, pymysql.cursors.Cursor]:
  56. if self._cursor is None or self._db is None:
  57. raise DBCloseException
  58. try:
  59. self._lock.acquire()
  60. self._cursor.execute(sql)
  61. except pymysql.MySQLError:
  62. self._db.rollback()
  63. return None
  64. finally:
  65. self._lock.release()
  66. return self._cursor
  67. def done_commit(self):
  68. try:
  69. self._lock.acquire()
  70. self._db.commit()
  71. finally:
  72. self._lock.release()