首页 技术 正文
技术 2022年11月23日
0 收藏 325 点赞 3,890 浏览 4191 个字

DBUtils 是一套用于管理数据库连接池的包,为高频度高并发的数据库访问提供更好的性能,可以自动管理连接对象的创建和释放。最常用的两个外部接口是 PersistentDB 和 PooledDB,前者提供了单个线程专用的数据库连接池,后者则是进程内所有线程共享的数据库连接池。

简介

DBUtils是一套Python数据库连接池包,并允许对非线程安全的数据库接口进行线程安全包装。DBUtils来自Webware for Python。

DBUtils提供两种外部接口:

  • PersistentDB :提供线程专用的数据库连接,并自动管理连接。
  • PooledDB :提供线程间可共享的数据库连接,并自动管理连接。

实测证明 PersistentDB 的速度是最高的,但是在某些特殊情况下,数据库的连接过程可能异常缓慢,而此时的PooledDB则可以提供相对来说平均连接时间比较短的管理方式。

另外,实际使用的数据库驱动也有所依赖,比如SQLite数据库只能使用PersistentDB作连接池。 下载地址:http://www.webwareforpython.org/downloads/DBUtils/

使用方法

连接池对象只初始化一次,一般可以作为模块级代码来确保。 PersistentDB的连接例子:

import DBUtils.PersistentDBpersist=DBUtils.PersistentDB.PersistentDB(dbpai=MySQLdb,maxusage=1000,**kwargs)

这里的参数dbpai指使用的底层数据库模块,兼容DB-API的。maxusage则为一个连接最大使用次数,参考了官方例子。后面的**kwargs则为实际传递给MySQLdb的参数。

获取连接: conn=persist.connection() 实际编程中用过的连接直接关闭 conn.close() 即可将连接交还给连接池。

PooledDB使用方法同PersistentDB,只是参数有所不同。

  • dbapi :数据库接口
  • mincached :启动时开启的空连接数量
  • maxcached :连接池最大可用连接数量
  • maxshared :连接池最大可共享连接数量
  • maxconnections :最大允许连接数量
  • blocking :达到最大数量时是否阻塞
  • maxusage :单个连接最大复用次数
  • setsession :用于传递到数据库的准备会话,如 [”set name UTF-8″] 。

一个使用过程:

db=pooled.connection()cur=db.cursor()cur.execute(sql)res=cur.fetchone()cur.close() # or del curdb.close() # or del db

python不用连接池的MySQL连接方法

import MySQLdbconn= 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 MySQLdbfrom DBUtils.PooledDB import PooledDBpool = PooledDB(MySQLdb,5,host='localhost',user='root',passwd='pwd',db='myDB',port=3306) #5为连接池里的最少连接数conn = pool.connection()  #以后每次需要数据库连接就是用connection()函数获取连接就好了cur=conn.cursor()SQL="select * from table1"r=cur.execute(SQL)r=cur.fetchall()cur.close()conn.close()

DBUtils下载地址:https://pypi.python.org/pypi/DBUtils/

测试代码:

import sysimport threadingimport MySQLdbimport DBUtils.PooledDBconnargs = { ", "db":"test" }def test(conn):    try:        cursor = conn.cursor()        count = cursor.execute("select * from users")        rows = cursor.fetchall()        for r in rows: pass    finally:        conn.close()def testloop():    print ("testloop")    for i in range(1000):        conn = MySQLdb.connect(**connargs)        test(conn)def testpool():    print ("testpool")    pooled = DBUtils.PooledDB.PooledDB(MySQLdb, **connargs)    for i in range(1000):        conn = pooled.connection()        test(conn)def main():    t = testloop if len(sys.argv) == 1 else testpool    for i in range(10):        threading.Thread(target = t).start()if __name__ == "__main__":    main()

看看 10 线程的测试结果。

$ time ./main.pytestlooptestlooptestlooptestlooptestlooptestlooptestlooptestlooptestlooptestloopreal    0m4.471suser    0m0.570ssys     0m4.670s$ time ./main.py -ltestpooltestpooltestpooltestpooltestpooltestpooltestpooltestpooltestpooltestpoolreal    0m2.637suser    0m0.320ssys     0m2.750s  

虽然测试方式不是很严谨,但从测试结果还是能感受到 DBUtils 带来的性能提升。当然,我们我们也可以在 testloop() 中一直重复使用一个不关闭的 Connection,但这却不适合实际开发时的情形。

DBUtils 提供了几个参数,便于我们更好地调整资源利用。

DBUtils.PooledDB.PooledDB(self, creator,    mincached=0, maxcached=0, maxshared=0, maxconnections=0, blocking=False, maxusage=None,    setsession=None, failures=None, *args, **kwargs)Docstring:    Set up the DB-API 2 connection pool.    creator: either an arbitrary function returning new DB-API 2        connection objects or a DB-API 2 compliant database module    mincached: initial number of idle connections in the pool        (0 means no connections are made at startup)    maxcached: maximum number of idle connections in the pool        (0 or None means unlimited pool size)    maxshared: maximum number of shared connections        (0 or None means all connections are dedicated)        When this maximum number is reached, connections are        shared if they have been requested as shareable.    maxconnections: maximum number of connections generally allowed        (0 or None means an arbitrary number of connections)    blocking: determines behavior when exceeding the maximum        (if this is set to true, block and wait until the number of        connections decreases, otherwise an error will be reported)    maxusage: maximum number of reuses of a single connection        (0 or None means unlimited reuse)        When this maximum usage number of the connection is reached,        the connection is automatically reset (closed and reopened).    setsession: optional list of SQL commands that may serve to prepare        the session, e.g. ["set datestyle to ...", "set time zone ..."]    failures: an optional exception class or a tuple of exception classes        for which the connection failover mechanism shall be applied,        if the default (OperationalError, InternalError) is not adequate    args, kwargs: the parameters that shall be passed to the creator        function or the connection constructor of the DB-API 2 module  

DBUtils 仅提供给了连接池管理,实际的数据库操作依然是由符合 DB-API 2 标准的目标数据库模块完成的。

 

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,028
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,518
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,365
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,146
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,780
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,857