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.PersistentDB
persist=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 cur
db.close() # or del db

python不用连接池的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为连接池里的最少连接数

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 sys
import threading
import MySQLdb
import DBUtils.PooledDB

connargs = { ", "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.py
testloop
testloop
testloop
testloop
testloop
testloop
testloop
testloop
testloop
testloop
real    0m4.471s
user    0m0.570s
sys     0m4.670s
$ time ./main.py -l
testpool
testpool
testpool
testpool
testpool
testpool
testpool
testpool
testpool
testpool
real    0m2.637s
user    0m0.320s
sys     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数据库连接池DBUtils.PooledDB的更多相关文章

  1. Python数据库连接池---DBUtils

    Python数据库连接池DBUtils   DBUtils是Python的一个用于实现数据库连接池的模块. 此连接池有两种连接模式: 模式一:为每个线程创建一个连接,线程即使调用了close方法,也不 ...

  2. Python数据库连接池DBUtils

    Python数据库连接池DBUtils   DBUtils是Python的一个用于实现数据库连接池的模块. 此连接池有两种连接模式: 模式一:为每个线程创建一个连接,线程即使调用了close方法,也不 ...

  3. Python数据库连接池实例——PooledDB

    不用连接池的MySQL连接方法 import MySQLdbconn= MySQLdb.connect(host='localhost',user='root',passwd='pwd',db='my ...

  4. Python 数据库连接池DButils

    常规的数据库链接存在的问题: 场景一: 缺点:每次请求反复创建数据库连接,连接数太多 import pymysql def index(): conn = pymysql.connect() curs ...

  5. Python数据库连接池DBUtils(基于pymysql模块连接数据库)

    安装 pip3 install DBUtils DBUtils是Python的一个用于实现数据库连接池的模块. 此连接池有两种连接模式: # BDUtils数据库链接池: 模式一:基于threaing ...

  6. Python数据库连接池DBUtils详解

    what's the DBUtils DBUtils 是一套用于管理数据库连接池的Python包,为高频度高并发的数据库访问提供更好的性能,可以自动管理连接对象的创建和释放.并允许对非线程安全的数据库 ...

  7. Python数据库连接池实例——PooledDB

    不用连接池的MySQL连接方法 import MySQLdb conn= MySQLdb.connect(host='localhost',user='root',passwd='pwd',db='m ...

  8. flask数据库连接池DBUtils

    数据库连接池 为啥要使用数据库连接池 频繁的连接和断开数据库,消耗大,效率低 DBUtils可以创建多个线程连接数据库,且一直保持连接,不会断开 执行数据库操作时,由数据池分配线程,当数据池空时,可选 ...

  9. python数据库连接池

    python数据库连接池 import psycopg2 import psycopg2.pool dbpool=psycopg2.pool.PersistentConnectionPool(1,1, ...

随机推荐

  1. Mina源码阅读笔记(五)—Mina对连接的操作IoSession

    IoSession是Mina管理两端的一个重要部分,也是Mina的核心,Session具有了生命周期的概念,它的生命周期和连接时紧密相关的,这点在后面的介绍中会涉及.另外,好像hibernate中也有 ...

  2. Windows平台安装及配置Hadoop(不借助cygwin)

    由于项目需要,我在VMware上装了几个虚拟机Windows server 2012 R2,并要搭建Hadoop集群.刚刚入门hadoop,一头雾水,然后开始搜各种教程,首先是选用cygwin进行安装 ...

  3. java面试题之分析(二)

    QUESTION NO:2 package com.cdu.test;  public class Test { static boolean foo(char c) { System.out.pri ...

  4. python爬虫——词云分析最热门电影《后来的我们》

    1 模块库使用说明 1.1 requests库 requests 是用Python语言编写,基于 urllib,采用 Apache2 Licensed 开源协议的 HTTP 库.它比 urllib 更 ...

  5. linux上nginx新建站点

    遇到一个要将后台部分模块剥离出来,重新放到一个新的后台上的问题: 这样一来,就要在服务器上新建站点,but,服务器是linux系统的,不是很熟,经过多方努力,搞定了 在这记录一下,用到的linux命令 ...

  6. 安装vmware tool时出错

    背景: 我想要在win10系统和vmware的ubuntu之间实现磁盘共享,从而实现文件共享.百度到可以通过安装vmware tools实现,所以着手安装vmware tools 问题: 安装vmwa ...

  7. Install and Configure Apache Kafka on Ubuntu 16.04

    https://devops.profitbricks.com/tutorials/install-and-configure-apache-kafka-on-ubuntu-1604-1/ by hi ...

  8. Java 面试知识点解析(二)——高并发编程篇

    前言: 在遨游了一番 Java Web 的世界之后,发现了自己的一些缺失,所以就着一篇深度好文:知名互联网公司校招 Java 开发岗面试知识点解析 ,来好好的对 Java 知识点进行复习和学习一番,大 ...

  9. 《T-SQL查询》读书笔记Part 1.逻辑查询处理知多少

    一.关于T-SQL T-SQL是ANSI和ISO SQL标准的MS SQL扩展,其正式名称为Transact-SQL,但一般程序员都称其为T-SQL. 二.逻辑查询处理各个阶段 2.1 逻辑查询处理流 ...

  10. 2、原生js实现轮播图特效

    很多很多网站经常会用到一个特效,那就是轮播图,对于日新月异的前端技术来说其实就是一个框架一个接口的事,但轮播的原理是什么?用最原始的javascript来写又是怎样的呢?本人是一枚菜鸟,这篇文章就当做 ...