这里只实现了部分功能,可以基于此工具类,加入更多功能,如事物、锁等。

  1. # db.py
  2. import pymysql
  3. from dbutils.pooled_db import PooledDB
  4. class DBHelper(object):
  5. def __init__(self):
  6. # TODO 此处配置,可以去配置文件中读取。
  7. self.pool = PooledDB(
  8. creator=pymysql, # 使用链接数据库的模块
  9. maxconnections=5, # 连接池允许的最大连接数,0和None表示不限制连接数
  10. mincached=2, # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
  11. maxcached=3, # 链接池中最多闲置的链接,0和None不限制
  12. blocking=True, # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
  13. setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
  14. ping=0,
  15. # ping MySQL服务端,检查是否服务可用。# 如:0 = None = never, 1 = default = whenever it is requested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
  16. host='127.0.0.1',
  17. port=3306,
  18. user='root',
  19. password='root',
  20. database='db1',
  21. charset='utf8'
  22. )
  23. def get_conn_cursor(self):
  24. conn = self.pool.connection()
  25. cursor = conn.cursor(pymysql.cursors.DictCursor)
  26. return conn, cursor
  27. def close_conn_cursor(self, *args):
  28. for item in args:
  29. item.close()
  30. def exec(self, sql, **kwargs):
  31. conn, cursor = self.get_conn_cursor()
  32. cursor.execute(sql, kwargs)
  33. conn.commit()
  34. self.close_conn_cursor(conn, cursor)
  35. def fetch_one(self, sql, **kwargs):
  36. conn, cursor = self.get_conn_cursor()
  37. cursor.execute(sql, kwargs)
  38. result = cursor.fetchone()
  39. self.close_conn_cursor(conn, cursor)
  40. return result
  41. def fetch_all(self, sql, **kwargs):
  42. conn, cursor = self.get_conn_cursor()
  43. cursor.execute(sql, kwargs)
  44. result = cursor.fetchall()
  45. self.close_conn_cursor(conn, cursor)
  46. return result
  47. db = DBHelper()
  1. from db import db
  2. db.exec("insert into d1(name) values(%(name)s)", name="武沛齐666")
  3. ret = db.fetch_one("select * from d1")
  4. print(ret)
  5. ret = db.fetch_one("select * from d1 where id=%(nid)s", nid=3)
  6. print(ret)
  7. ret = db.fetch_all("select * from d1")
  8. print(ret)
  9. ret = db.fetch_all("select * from d1 where id>%(nid)s", nid=2)
  10. print(ret)

上下文管理

如果你想要让他也支持 with 上下文管理。
好处:多个SQL共用同一个连接,进一步提升性能。

  1. with 获取连接:
  2. 执行SQL(执行完毕后,自动将连接交还给连接池)
  1. # db_context.py
  2. import threading
  3. import pymysql
  4. from dbutils.pooled_db import PooledDB
  5. POOL = PooledDB(
  6. creator=pymysql, # 使用链接数据库的模块
  7. maxconnections=5, # 连接池允许的最大连接数,0和None表示不限制连接数
  8. mincached=2, # 初始化时,链接池中至少创建的空闲的链接,0表示不创建
  9. maxcached=3, # 链接池中最多闲置的链接,0和None不限制
  10. blocking=True, # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
  11. setsession=[], # 开始会话前执行的命令列表。如:["set datestyle to ...", "set time zone ..."]
  12. ping=0,
  13. host='127.0.0.1',
  14. port=3306,
  15. user='root',
  16. password='root',
  17. database='db1',
  18. charset='utf8'
  19. )
  20. class Connect(object):
  21. def __init__(self):
  22. self.conn = conn = POOL.connection()
  23. self.cursor = conn.cursor(pymysql.cursors.DictCursor)
  24. def __enter__(self):
  25. return self
  26. def __exit__(self, exc_type, exc_val, exc_tb):
  27. self.cursor.close()
  28. self.conn.close()
  29. def exec(self, sql, **kwargs):
  30. self.cursor.execute(sql, kwargs)
  31. self.conn.commit()
  32. def fetch_one(self, sql, **kwargs):
  33. self.cursor.execute(sql, kwargs)
  34. result = self.cursor.fetchone()
  35. return result
  36. def fetch_all(self, sql, **kwargs):
  37. self.cursor.execute(sql, kwargs)
  38. result = self.cursor.fetchall()
  39. return result
  1. from db_context import Connect
  2. with Connect() as obj:
  3. # print(obj.conn)
  4. # print(obj.cursor)
  5. ret = obj.fetch_one("select * from d1")
  6. print(ret)
  7. ret = obj.fetch_one("select * from d1 where id=%(id)s", id=3)
  8. print(ret)