时间:2021-07-01 10:21:17 帮助过:11人阅读
python3 -m pip install DBUtils去安装DBUtils库

通过连接池的方式去创建数据库对象:
这里参考我的上一篇博客:http://www.cnblogs.com/letmeiscool/p/8434381.html和DBUtils用户指南:http://blog.csdn.net/gashero/article/details/1577187去写。单独写了个创建连接池的方法,在创建数据库对象的时候被执行。之后每次去执行sql的时候,不需要去创建连接池,只需要每次执行sql前去执行连接方法_Getconnect,sql执行完毕,去关闭连接,连接被数据库连接池给回收。
#-*-coding:utf-8-*-s
#mysql和sqlserver的库
import pymysql,pymssql
from DBUtils.PooledDB import PooledDB
class Database:
def __init__(self,*db):
if len(db)==5:
#mysql数据库
self.host=db[0]
self.port=db[1]
self.user=db[2]
self.pwd=db[3]
self.db=db[4]
else:
#sqlserver数据库
self.host=db[0]
self.port=None
self.user=db[1]
self.pwd=db[2]
self.db=db[3]
self._CreatePool()
def _CreatePool(self):
if not self.db:
raise NameError+"没有设置数据库信息"
if (self.port==None):
self.Pool=PooledDB(creator=pymssql,mincached=2, maxcached=5,maxshared=3, maxconnections=6, blocking=True,host=self.host,user=self.user, password=self.pwd,database=self.db,charset="utf8")
else:
self.Pool=PooledDB(creator=pymysql,mincached=2, maxcached=5,maxshared=3, maxconnections=6, blocking=True,host=self.host,port=self.port, user=self.user,password=self.pwd,database =self.db,charset="utf8")
def _Getconnect(self):
self.conn=self.Pool.connection()
cur=self.conn.cursor()
if not cur:
raise "数据库连接不上"
else:
return cur
#查询sql
def ExecQuery(self,sql):
cur=self._Getconnect()
cur.execute(sql)
relist=cur.fetchall()
cur.close()
self.conn.close()
return relist
#非查询的sql
def ExecNoQuery(self,sql):
cur=self._Getconnect()
cur.execute(sql)
self.conn.commit()
cur.close()
self.conn.close()
PooledDB的参数:
python数据库连接池
标签:span utils 限制 lock 会话 error details log bubuko