这篇文章将为大家详细讲解有关Python中怎么实现数据库连接池,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。
示例:
#-*-coding:utf-8-*- import threading,time,datetime import MySQLdb from DBUtils import PooledDB 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 代表不限制)如果我现在将代码调整如下:
#-*-coding:utf-8-*- import threading,time,datetime import MySQLdb from DBUtils import PooledDB pool = PooledDB.PooledDB(MySQLdb,100,50,100,400,False,host='localhost',user='root',passwd='321',db='test',charset='utf8') 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(402): obj = MyThread(str(i)) obj.start()
关于Python中怎么实现数据库连接池就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。
亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。