重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

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

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

创新互联公司长期为1000+客户提供的网站建设服务,团队从业经验10年,关注不同地域、不同群体,并针对不同对象提供差异化的产品和服务;打造开放共赢平台,与合作伙伴共同营造健康的互联网生态环境。为青河企业提供专业的网站设计、成都做网站青河网站改版等技术服务。拥有十多年丰富建站经验和众多成功案例,为您定制开发。

示例:

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


分享名称:Python中怎么实现数据库连接池
链接地址:http://cqcxhl.cn/article/jdejgs.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP