mysql_db.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import pymysql
  2. import threading
  3. import traceback
  4. from conf import mysql_url, mysql_name, mysql_passwd
  5. from .base_db import Database, DBCloseException
  6. from tool.type_ import *
  7. class MysqlDB(Database):
  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, sql) -> Union[None, pymysql.cursors.Cursor]:
  33. if self._cursor is None or self._db is None:
  34. raise DBCloseException
  35. try:
  36. self._lock.acquire() # 上锁
  37. self._cursor.execute(sql)
  38. except pymysql.MySQLError:
  39. return None
  40. finally:
  41. self._lock.release() # 释放锁
  42. return self._cursor
  43. def done(self, sql) -> Union[None, pymysql.cursors.Cursor]:
  44. if self._cursor is None or self._db is None:
  45. raise DBCloseException
  46. try:
  47. self._lock.acquire()
  48. self._cursor.execute(sql)
  49. except pymysql.MySQLError:
  50. self._db.rollback()
  51. traceback.print_exc()
  52. return None
  53. finally:
  54. self._db.commit()
  55. self._lock.release()
  56. return self._cursor
  57. def done_(self, sql) -> Union[None, pymysql.cursors.Cursor]:
  58. if self._cursor is None or self._db is None:
  59. raise DBCloseException
  60. try:
  61. self._lock.acquire()
  62. self._cursor.execute(sql)
  63. except pymysql.MySQLError:
  64. self._db.rollback()
  65. return None
  66. finally:
  67. self._lock.release()
  68. return self._cursor
  69. def done_commit(self):
  70. try:
  71. self._lock.acquire()
  72. self._db.commit()
  73. finally:
  74. self._lock.release()