python模块之 DBUtils连接池实现的2种模式

DBUtils_ 是一套允许线程化 Python_ 程序可以安全和有效的访问数据库的模块。DBUtils已经作为 Webware for Python_ 一部分用来结合 PyGreSQL_ 访问 PostgreSQL_ 数据库,当然他也可以用在其他Python应用程序中来访问 DB-API 2_ 兼容的数据库接口。

DBUtils 的两种连接模式:
1、DBUtils.PersistentDB

Generator for persistent DB-API 2 connections.
After you have created the connection pool, you can use connection() to get thread-affine, steady DB-API 2 connections.

2、DBUtils.PooledDB

Pool for DB-API 2 connections.
After you have created the connection pool, you can use connection() to get pooled, steady DB-API 2 connections.
from DBUtils.PersistentDB import PersistentDB
import pymysql
# help(pymysql.cursors)
class mysqlPool():
    def __init__(self):
        self.conn = self.__connect()
        self.cur = self.conn.cursor()
    def __connect(self):
        POOL = PersistentDB(
            creator=pymysql,  # 使用链接数据库的模块
            maxusage=None,  # 一个链接最多被重复使用的次数,None表示无限制
            setsession=[],  # 开始会话前执行的命令列表。
            ping=0,
            # ping MySQL服务端,检查是否服务可用。
            closeable=False,
            # 如果为False时, conn.close() 实际上被忽略,供下次使用,再线程关闭时,才会自动关闭链接。如果为True时, conn.close()则关闭链接,那么再次调用pool.connection时就会报错,因为已经真的关闭了连接(pool.steady_connection()可以获取一个新的链接)
            threadlocal=None,  # 本线程独享值得对象,用于保存链接对象,如果链接对象被重置
            host='192.168.2.201',
            port=3306,
            user='bbs',
            password='bbs123',
            database='bbs',
            charset='utf8'
        )
        # print('............1..................')
        return POOL.connection()
    def run(self):
        # conn = self.connection(shareable=False)
        print('...............2................')
        # cursor = self.conn.cursor()
        self.cur.execute('select * from app_test')
        result = self.cur.fetchall()
        print(result)
        # self.cur.close()
    def closeConn(self):
        self.conn.close()
if __name__ == '__main__':
    t = mysqlPool()
    t.run()
    t.closeConn()

猜你喜欢

转载自blog.csdn.net/q936889811/article/details/80605769