版本环境
- python 3.7
- DBUtils 1.3
- mysqlclient 1.4.6
连接池初始化
pool = PooledDB(creator=MySQLdb, mincached=0, maxcached=0,
maxshared=0, maxconnections=0, blocking=False,
maxusage=None, setsession=None, reset=True,
failures=None, ping=1,
*args, **kwargs)
参数说明
- creator
#creator => 任何符合DB-API 2.0规范的函数或者兼容的数据库模块
- mincached
#mincached => 初始化时,链接池中至少创建的空闲的链接,0表示不创建
- maxcached
#maxcached => 链接池中最大闲置的链接数(0和None不限制)
- maxshared
#maxshared => maximum number of shared connections
(0 or None means all connections are dedicated)
When this maximum number is reached, connections are
shared if they have been requested as shareable
- maxconnections
#maxconnections => 允许的最大链接数(0或None表示不限制)
- blocking
#blocking => 链接池没有可用链接后,是否阻塞等待。
True表示阻塞等待,直到获取到链接;
False不等待,抛异常退出
- maxusage
#maxusage => 同一个链接最多被重复使用的次数(0和None表示无限制)
- setsession
#setsession => 可选的会话命令:开始会话前执行的命令列表。
例如["set datestyle to…","set time zone…"]
- reset
#reset => 当连接放回池中时,重置连接的方式,默认为True。
False或者None表示使用begin()开启了事务的链接,会执行回滚;
安全起见,建议使用True,当为True时表示所有链接都执行回滚操作
- failures
#failures => 当默认的(OperationalError,InternalError)异常不能满足要求时,
可以自定义抛出异常:默认为None;
自定义为传入的为tuple或者issubclass(failures, Exception)
- ping
#ping => 检查连接是否仍然处于活动状态的方式
0 = None = never,
1 = default = whenever fetched from the pool,
2 = when a cursor is created,
4 = when a query is executed,
7 = always, and all other bit combinations of these values
- args, kwargs
#args, kwargs => 传递给creator的参数
使用
# -*- coding: utf-8 -*-
# @Time : 2020/1/26 0026 20:28
# @Email : lofish@foxmail.com(撸小鱼)
import MySQLdb
import MySQLdb.cursors
from DBUtils.PooledDB import PooledDB
import datetime
class DbManager(object):
def __init__(self, host, port, db_name, user_name, password):
cmds = ["set names utf8mb4;"]
conn_args = {'host': host,
'port': port,
'db': db_name,
'user': user_name,
'passwd': password,
'charset': 'utf8',
'cursorclass': MySQLdb.cursors.DictCursor
}
# 初始化时,链接池中至少创建的空闲的链接,0表示不创建,mincached: 5
# 链接池中最大闲置的链接数(0和None不限制): 20
self._pool = PooledDB(MySQLdb, mincached=5, maxcached=20, setsession=cmds, **conn_args)
def connection(self):
return self._pool.connection()
_db_manager = None
def create_db_manager(host, port, dbname, username, password):
global _db_manager
if _db_manager is None:
_db_manager = DbManager(host, port, dbname, username, password)
return _db_manager