温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python中怎么实现数据库连接池

发布时间:2021-06-25 15:29:02 来源:亿速云 阅读:247 作者:Leah 栏目:编程语言

这篇文章将为大家详细讲解有关Python中怎么实现数据库连接池,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

示例:

  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')   

默认打开的时候就创建了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 代表不限制)如果我现在将代码调整如下:

  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()   

关于Python中怎么实现数据库连接池就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI