下面的内容主要是介绍Python数据库连接池应用于多线程环境中使用的具体方案的具体介绍。如果你对Python数据库连接池在其具体方案应用的相关步骤感兴趣的话,你就可以点击以下的文章,对其进行了解。
示例:
- #-*-coding:utf-8-*-
- import threading,time,datetime
- import MySQLdb
- from DBUtils import PooledDB
- pool = PooledDB.PooledDB(MySQLdb,100,50,100,490,False,
host='localhost',user='root',passwd='321',db='test',
charset='utf8')
默认打开的时候就创建了100个数据库连接。检查发现果然数据库中有100个
- class MyThread(threading.Thread):
- def __init__(self,threadName):
- self.conn = pool.connection()
直接从数据库连接池中提取
- threading.Thread.__init__(self,name=threadName)
- def run(self):
- cursor=self.conn.cursor()
- print "hello--->",self.getName()
- file_objct = open('8.txt','a+')
- file_objct.write(self.getName()+'\n')
- file_objct.close()
- #cursor.execute("call loaddate();")
- #self.conn.commit()
- time.sleep(10)
- def __del__(self):
- self.conn.close()
- self.conn = None
- for i in range(5):
- obj = MyThread(str(i))
- obj.start()
如果我开480个线程的话 数据库显示的正是480个连接!maxconnections: ***允许连接数量(缺省值 0 代表不限制)如果我现在将代码调整如下:
- #-*-coding:utf-8-*-
- import threading,time,datetime
- import MySQLdb
- from DBUtils import PooledDB
- pool = PooledDB.PooledDB(MySQLdb,100,50,100,400,False,
host='localhost',user='root',passwd='321',db='test',
charset='utf8')- class MyThread(threading.Thread):
- def __init__(self,threadName):
- self.conn = pool.connection()
- threading.Thread.__init__(self,name=threadName)
- def run(self):
- cursor=self.conn.cursor()
- print "hello--->",self.getName()
- file_objct = open('8.txt','a+')
- file_objct.write(self.getName()+'\n')
- file_objct.close()
- #cursor.execute("call loaddate();")
- #self.conn.commit()
- time.sleep(10)
- def __del__(self):
- self.conn.close()
- self.conn = None
- for i in range(402):
- obj = MyThread(str(i))
- obj.start()
连接池***的数目才400 。
【编辑推荐】