MysqlUtils.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. return __pool
  24. def query(self,sql):
  25. con = None
  26. cur = None
  27. try:
  28. con = self.pool.connection()
  29. cur = con.cursor()
  30. count = cur.execute(sql)
  31. if count > 0:
  32. result = cur.fetchall()
  33. result = [[j.decode() if isinstance(j,bytes) else j for j in i] for i in result]
  34. print(result)
  35. else:
  36. result = False
  37. return result
  38. except Exception as e:
  39. print(e)
  40. finally:
  41. if cur:
  42. cur.close()
  43. if con:
  44. con.close()
  45. def update(self,sql):
  46. con = None
  47. cur = None
  48. try:
  49. con = self.pool.connection()
  50. cur = con.cursor()
  51. cur.execute(sql)
  52. con.commit()
  53. except Exception as e:
  54. con.rollback() # 事务回滚
  55. print(e)
  56. finally:
  57. if cur:
  58. cur.close()
  59. if con:
  60. con.close()
  61. def close(self):
  62. if MysqlUtils.__pool:
  63. MysqlUtils.__pool.close()