溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Python中怎么實(shí)現(xiàn)數(shù)據(jù)庫連接池

發(fā)布時(shí)間:2021-06-25 15:29:02 來源:億速云 閱讀:251 作者:Leah 欄目:編程語言

這篇文章將為大家詳細(xì)講解有關(guān)Python中怎么實(shí)現(xiàn)數(shù)據(jù)庫連接池,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個(gè)參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

示例:

  1. #-*-coding:utf-8-*-  

  2. import threading,time,datetime  

  3. import MySQLdb  

  4. from DBUtils import PooledDB  

  5. 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)整如下:

  1. #-*-coding:utf-8-*-  

  2. import threading,time,datetime  

  3. import MySQLdb  

  4. from DBUtils import PooledDB  

  5. pool = PooledDB.PooledDB(MySQLdb,100,50,100,400,False,
    host='localhost',user='root',passwd='321',db='test',
    charset='utf8')  

  6. class MyThread(threading.Thread):  

  7. def __init__(self,threadName):  

  8. self.conn = pool.connection()   

  9. threading.Thread.__init__(self,name=threadName)  

  10. def run(self):  

  11. cursor=self.conn.cursor()  

  12. print "hello--->",self.getName()  

  13. file_objct = open('8.txt','a+')  

  14. file_objct.write(self.getName()+'\n')  

  15. file_objct.close()  

  16. #cursor.execute("call loaddate();")  

  17. #self.conn.commit()  

  18. time.sleep(10)  

  19. def __del__(self):  

  20. self.conn.close()  

  21. self.conn = None   

  22. for i in range(402):  

  23. obj = MyThread(str(i))  

  24. obj.start()   

關(guān)于Python中怎么實(shí)現(xiàn)數(shù)據(jù)庫連接池就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(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)容。

AI