1 )概述
2 )示例演示
import threading
import pymysql
from dbutils.pooled_db import PooledDB
MYSQL_DB_POOL = PooledDB(
creator=pymysql, # 使用连接数据库的模块
maxconnection=5, # 连接池允许的最大连接数,0 和 None 表示不限制连接数
mincached=2, # 初始化时,连接池中至少创建的空闲的连接,0表示不创建
maxcached=3, # 连接池中最多闲置的连接,0 和 None 不限制
blocking=True, # 连接池中如果没有可用连接后,是否阻塞等待。True, 等待: False, 不等待然后报错
setsession=[], # 开始会花钱执行的命令列表,如: ["set datestyle to ...", "set time zone ..."]
ping=0, # 没必要做连接前的检查, 0 = None = never, 1 = default = whenever it is rquested, 2 = when a cursor is created, 4 = when a query is executed, 7 = always
host='127.0.0.1',
port=3306,
user='root',
password='xxxx',
database='userdb'
charset='utf8'
)
def task():
# 去连接池获取一连接, 有则获取,无则阻塞
conn = MYSQL_DB_POOL.connection()
cursor = cursor(pymysql.cursors.DictCursor)
cursor.execute('select sleep(2)')
result = cursor.fetchall()
cursor.close()
conn.close() # 将连接还给连接池
def run():
# 开始并发请求
for i in range(10):
t = threading.Thread(target=task)
t.start()
if __name__ == '__main__':
run()