环境
pip install pymysql
pip install dbutils
1 单线程测试
import pymysql
from dbutils.pooled_db import PooledDB
pool = PooledDB(
creator=pymysql,
maxconnections=6,
blocking=True,
ping=1,
host='localhost',
port=3306,
user='root',
password='root',
database='test'
)
conn = pool.connection()
cursor = conn.cursor()
cursor.execute('select version()')
res = cursor.fetchall()
print(res)
cursor.close()
conn.close()
2 多线程模拟
import pymysql
from dbutils.pooled_db import PooledDB
pool = PooledDB(
creator=pymysql,
maxconnections=6,
blocking=True,
ping=1,
host='localhost',
port=3306,
user='root',
password='root',
database='test'
)
def task(i):
conn = pool.connection()
cursor = conn.cursor()
cursor.execute('select sleep(3)')
res = cursor.fetchall()
print(f'线程{i}'+ '----->' + str(res))
cursor.close()
conn.close()
from threading import Thread
for i in range(50):
Thread(target=task, args=(i, )).start()
每六个线程做为一组获取链接,使用完之后将链接还给链接池
|