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 。

评论关闭