打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Python数据库连接池相关示例详细介绍

Python数据库连接池相关示例详细介绍


以下的内容主要是介绍Python数据库连接池应用于多线程环境中使用的具体方案的具体介绍。你就可以点击以下的文章,对其进行了解。

下面的内容主要是介绍Python数据库连接池应用于多线程环境中使用的具体方案的具体介绍。如果你对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个

  1. class MyThread(threading.Thread):  
  2. def __init__(self,threadName):  
  3. self.conn = pool.connection()    

直接从数据库连接池中提取

  1. threading.Thread.__init__(self,name=threadName)  
  2. def run(self):  
  3. cursor=self.conn.cursor()  
  4. print "hello--->",self.getName()  
  5. file_objct = open('8.txt','a+')  
  6. file_objct.write(self.getName()+'\n')  
  7. file_objct.close()  
  8. #cursor.execute("call loaddate();")  
  9. #self.conn.commit()  
  10. time.sleep(10)  
  11. def __del__(self):  
  12. self.conn.close()  
  13. self.conn = None   
  14. for i in range(5):  
  15. obj = MyThread(str(i))  
  16. obj.start()  
  17.  

如果我开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()   

连接池最大的数目才400 。

来自:http://developer.51cto.com/art/201003/189679.htm


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
python操作sqlite示例(支持多进程/线程同时操作) - 学步园
Python+MongoDB导入股票日线及分钟线数据
python:利用pymssql模块操作SQL server数据库
UC头条:Python 为什么要使用数据库连接池, MySQL PooledDB 简单使用
数据库连接和数据库池
Python3操作:借助Pycharm快速连接并操作mysql数据库
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服