MysqlUtils.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import pymysql
  2. from dbutils.pooled_db import PooledDB
  3. class MysqlUtils():
  4. # 连接池对象
  5. __pool = None
  6. def __init__(self,**config):
  7. self.host = config["host"]
  8. self.port = int(config["port"])
  9. self.user = config["user"]
  10. self.passwd = config["passwd"]
  11. self.database = None
  12. if "database" in config:
  13. self.database = config["database"]
  14. # self.pool = self.get_conn()
  15. self.pool = None
  16. def get_conn(self):
  17. if MysqlUtils.__pool is None:
  18. __pool = PooledDB(pymysql, mincached=1, maxcached=5, maxconnections=5,
  19. host=self.host, port=self.port, user=self.user, passwd=self.passwd,
  20. database=self.database,
  21. use_unicode=False, blocking=False, charset="utf8")
  22. self.pool = __pool
  23. def query(self,sql):
  24. con = None
  25. cur = None
  26. try:
  27. con = self.pool.connection()
  28. cur = con.cursor()
  29. count = cur.execute(sql)
  30. if count >= 0:
  31. result = cur.fetchall()
  32. result = [[j.decode() if isinstance(j,bytes) else j for j in i] for i in result]
  33. # print(result)
  34. else:
  35. result = False
  36. return result
  37. except Exception as e:
  38. print(e)
  39. finally:
  40. if cur:
  41. cur.close()
  42. if con:
  43. con.close()
  44. def update(self,sql):
  45. con = None
  46. cur = None
  47. try:
  48. con = self.pool.connection()
  49. cur = con.cursor()
  50. cur.execute(sql)
  51. con.commit()
  52. except Exception as e:
  53. con.rollback() # 事务回滚
  54. print(e)
  55. finally:
  56. if cur:
  57. cur.close()
  58. if con:
  59. con.close()
  60. def close(self):
  61. if MysqlUtils.__pool:
  62. MysqlUtils.__pool.close()