您好,登錄后才能下訂單哦!
這篇文章將為大家詳細(xì)講解有關(guān)Python中怎么實(shí)現(xiàn)數(shù)據(jù)庫連接池,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對相關(guā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)打開的時(shí)候就創(chuàng)建了100個(gè)數(shù)據(jù)庫連接。檢查發(fā)現(xiàn)果然數(shù)據(jù)庫中有100個(gè)
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個(gè)線程的話 數(shù)據(jù)庫顯示的正是480個(gè)連接!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()
關(guān)于Python中怎么實(shí)現(xiàn)數(shù)據(jù)庫連接池就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。