Python數據庫連接池相關示例詳細介紹
作者:佚名
以下的內容主要是介紹Python數據庫連接池應用于多線程環境中使用的具體方案的具體介紹。你就可以點擊以下的文章,對其進行了解。
下面的內容主要是介紹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 。
【編輯推薦】
責任編輯:佚名
來源:
互聯網