python怎么使用mysql数据库连接池

python怎么使用mysql数据库连接池,第1张

import MySQLdb

import time

import string

import redis

class PooledConnection:

#构建连接池实例

def __init__(self, maxconnections, connstr,dbtype):

from Queue import Queue

self._pool = Queue(maxconnections) # create the queue

self.connstr = connstr

self.dbtype=dbtype

self.maxconnections=maxconnections

#根据你给数目来创建链接,并且写入刚才创建的队列里面。

try:

for i in range(maxconnections):

self.fillConnection(self.CreateConnection(connstr,dbtype))

except Exception,e:

raise e

def fillConnection(self,conn):

try:

self._pool.put(conn)

except Exception,e:

raise "fillConnection error:"+str(e)

def returnConnection(self, conn):

try:

self._pool.put(conn)

except Exception,e:

raise "returnConnection error:"+str(e)

def getConnection(self):

try:

return self._pool.get()

except Exception,e:

raise "getConnection error:"+str(e)

def ColseConnection(self,conn):

try:

self._pool.get().close()

self.fillConnection(self.CreateConnection(connstr,dbtype))

except Exception,e:

raise "CloseConnection error:"+str(e)

不用连接池的MySQL连接方法

import MySQLdb

conn= MySQLdb.connect(host='localhost',user='root',passwd='pwd',db='myDB',port=3306)

cur=conn.cursor()

SQL="select * from table1"

r=cur.execute(SQL)

r=cur.fetchall()

cur.close()

conn.close()

用连接池后的连接方法

import MySQLdb

from DBUtils.PooledDB import PooledDB

pool = PooledDB(MySQLdb,5,host='localhost',user='root',passwd='pwd',db='myDB',port=3306) #5为连接池里的最少连接数


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/9251452.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-26
下一篇 2023-04-26

发表评论

登录后才能评论

评论列表(0条)

保存