Python数据库连接池DButils
DButils
DButils是python的一个实现数据库连接池的模块
两种模式:
1.为每一个线程创建一个链接,即使线程即使调用了close()方法,也不会关闭,只是把线程放到连接池,供自己再次使用,当连接关闭时,线程连接自动关闭。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
2.创建一批连接到连接池,供所有线程共享使用
注意:由于pymysql,mysqlDB中的threadsafety值为1,所有线程共享连接
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
PS:关于pymysql模块,如果没有单线程的情况,连接MySQL数据库没有问题,但如果要是多线程,就需要加锁,一旦加锁,后面的线程就得等待,势必会降低使用效率。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import pymysql 2 import threading 3 from threading import RLock 4 LOCK = RLock() 5 CONN = pymysql.connect(host='127.0.0.1', 6 port = 3306, 7 user = 'root', 8 password = '123', 9 database = 'ok1', 10 charset = 'utf8' 11 ) 12 def task(arg): 13 with LOCK: 14 cursor = CONN.cursor() 15 cursor.execute('select * from book') 16 result = cursor.fetchall() 17 cursor.close() 18 print(result) 19 for i in range(10): 20 t = threading.Thread(target=task,args=(i,)) 21 t.start()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 import pymysql 2 import threading 3 CONN = pymysql.connect(host='127.0.0.1', 4 port=3306, 5 user='root', 6 password='123', 7 database='ok1', 8 charset='utf8') 9 10 def task(arg): 11 cursor = CONN.cursor() 12 cursor.execute('select * from book') 13 result = cursor.fetchall() 14 cursor.close() 15 print(result) 16 for i in range(10): #1时不会报错 17 t = threading.Thread(target=task, args=(i,)) 18 t.start()