Python數(shù)據(jù)庫連接池相關(guān)示例詳細(xì)介紹
下面的內(nèi)容主要是介紹Python數(shù)據(jù)庫連接池應(yīng)用于多線程環(huán)境中使用的具體方案的具體介紹。如果你對Python數(shù)據(jù)庫連接池在其具體方案應(yīng)用的相關(guān)步驟感興趣的話,你就可以點擊以下的文章,對其進(jìn)行了解。
示例:
- #-*-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')
默認(rèn)打開的時候就創(chuàng)建了100個數(shù)據(jù)庫連接。檢查發(fā)現(xiàn)果然數(shù)據(jù)庫中有100個
- class MyThread(threading.Thread):
- def __init__(self,threadName):
- self.conn = pool.connection()
直接從數(shù)據(jù)庫連接池中提取
- 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個線程的話 數(shù)據(jù)庫顯示的正是480個連接!maxconnections: ***允許連接數(shù)量(缺省值 0 代表不限制)如果我現(xiàn)在將代碼調(diào)整如下:
- #-*-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()
連接池***的數(shù)目才400 。
【編輯推薦】