python DbUtils 封装

python DbUtils 封装

1.python dbutils 说明:

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

DBUtils提供两种外部接口:
* PersistentDB :提供线程专用的数据库连接,并自动管理连接。
* PooledDB :提供线程间可共享的数据库连接,并自动管理连接。
需要库
1、DBUtils pip install DBUtils
2、pymysql pip install pymysql/MySQLdb

MyDbUtils:

#-*- coding: UTF-8 -*-
import pymysql
from DBUtils.PooledDB import PooledDB
import DB_config as Config
import MySQLdb
'''
@功能:PT数据库连接池
'''
class PTConnectionPool(object):
    __pool = None;
    # def __init__(self):
    #     self.conn = self.__getConn();
    #     self.cursor = self.conn.cursor();
    def __enter__(self):
        self.conn = self.__getConn();
        self.cursor = self.conn.cursor();
        print u"PT数据库创建con和cursor";
        return self;

    def __getConn(self):
        if self.__pool is None:
            self.__pool = PooledDB(creator=MySQLdb, mincached=Config.DB_MIN_CACHED , maxcached=Config.DB_MAX_CACHED,
                               maxshared=Config.DB_MAX_SHARED, maxconnections=Config.DB_MAX_CONNECYIONS,
                               blocking=Config.DB_BLOCKING, maxusage=Config.DB_MAX_USAGE,
                               setsession=Config.DB_SET_SESSION,
                               host=Config.DB_TEST_HOST , port=Config.DB_TEST_PORT ,
                               user=Config.DB_TEST_USER , passwd=Config.DB_TEST_PASSWORD ,
                               db=Config.DB_TEST_DBNAME , use_unicode=False, charset=Config.DB_CHARSET);
    return self.__pool.connection()
"""
@summary: 释放连接池资源
"""
def __exit__(self, type, value, trace):
    self.cursor.close()
    self.conn.close()
    print u"PT连接池释放con和cursor";

#重连接池中取出一个连接
def getconn(self):
    conn = self.__getConn();
    cursor = conn.cursor();
    return cursor,conn

#关闭连接归还给连接池
# def close(self):
#     self.cursor.close()
#     self.conn.close()
#     print u"PT连接池释放con和cursor";


def getPTConnection():
    return PTConnectionPool()

配置文件:DB_config.py

#-*- coding: UTF-8 -*-

#TEST数据库信息
DB_TEST_HOST="192.168.88.6";
DB_TEST_PORT=3306;
DB_TEST_DBNAME="asterisk";
DB_TEST_USER="root";
DB_TEST_PASSWORD="kalamodo";


#数据库连接编码
DB_CHARSET="utf8";

#mincached : 启动时开启的闲置连接数量(缺省值 0 开始时不创建连接)
DB_MIN_CACHED=10;

#maxcached : 连接池中允许的闲置的最多连接数量(缺省值 0 代表不闲置连接池大小)
DB_MAX_CACHED=10;

#maxshared : 共享连接数允许的最大数量(缺省值 0 代表所有连接都是专用的)如果达到了最大数量,被请求为共享的连接将会被共享使用
DB_MAX_SHARED=20;

#maxconnecyions : 创建连接池的最大数量(缺省值 0 代表不限制)
DB_MAX_CONNECYIONS=100;

#blocking : 设置在连接池达到最大数量时的行为(缺省值 0 或 False 代表返回一个错误<toMany......>; 其他代表阻塞直到连接数减少,连接被分配)
DB_BLOCKING=True;

#maxusage : 单个连接的最大允许复用次数(缺省值 0 或 False 代表不限制的复用).当达到最大数时,连接会自动重新连接(关闭和重新打开)
DB_MAX_USAGE=0;

#setsession : 一个可选的SQL命令列表用于准备每个会话,如["set datestyle to german", ...]
DB_SET_SESSION=None;

封装的mysqlhelp.py

coding=utf-8

import MySQLdb
from MyDbUtils import getPTConnection

class MysqlHelp(object):

mysql=None
def __init__(self):
    # self.connect()
    self.db=getPTConnection()
def __new__(cls, *args, **kwargs):
    if not hasattr(cls, 'inst'):
        cls.inst = super(MysqlHelp, cls).__new__(cls, *args, **kwargs)
    return cls.inst
#查询所有
def selectall(self,sql='',param=()):
    #判断是否连接,并设置重连机制
    # self.connected()
    try:
        cursor,conn=self.execute(sql,param)
        res=cursor.fetchall()
        self.close(cursor, conn)
        return res
    except Exception,e:
        print 'selectall except   ', e.args
        self.close(cursor, conn)
        return None

#查询一条
def selectone(self,sql='',param=()):
    # self.connected()
    try:
        # cur = self.db.cursor()
        cursor, conn=self.execute(sql,param)
        res = cursor.fetchone()
        self.close(cursor, conn)
        return res
    except Exception, e:
        print 'selectone except   ', e.args
        self.close(cursor, conn)
        return None

#增加
def insert(self,sql='',param=()):
    # self.connected()
    try:
        # self.db.getconn().execute(sql, param)
        cursor, conn=self.execute(sql,param)
        print '============'
        # _id=self.db.conn.insert_id()
        _id=cursor.lastrowid
        print '_id   ',_id
        conn.commit()
        self.close(cursor, conn)
        #防止表中没有id返回0
        if _id==0:
            return True
        return _id
    except Exception, e:
        print 'insert except   ', e.args
        conn.rollback()
        self.close(cursor, conn)
        # self.conn.rollback()
        return 0

#增加多行
def insertmany(self,sql='',param=()):
    # self.connected()
    cursor,conn=self.db.getconn()
    try:
        cursor.executemany(sql, param)
        # self.execute(sql,param)
        conn.commit()
        self.close(cursor, conn)
        return True
    except Exception, e:
        print 'insert many except   ', e.args
        conn.rollback()
        self.close(cursor, conn)
        # self.conn.rollback()
        return False

#删除
def delete(self,sql='',param=()):
    # self.connected()
    try:
        # cur = self.conn.cursor()
        # self.db.getconn().execute(sql, param)
        cursor,conn=self.execute(sql,param)
        # self.db.conn.commit()
        self.close(cursor, conn)
        return True
    except Exception, e:
        print 'delete except   ', e.args
        conn.rollback()
        self.close(cursor, conn)
        # self.conn.rollback()
        return False

#更新
def update(self,sql='',param=()):
    # self.connected()
    try:
        #cur = self.conn.cursor()
        # self.db.getconn().execute(sql, param)
        cursor,conn=self.execute(sql,param)
        # self.db.conn.commit()
        self.close(cursor, conn)
        return True
    except Exception, e:
        print 'update except   ',e.args
        conn.rollback()
        self.close(cursor, conn)
        # self.conn.rollback()
        return False

@classmethod
def getInstance(self):
    if MysqlHelp.mysql==None:
        MysqlHelp.mysql=MysqlHelp()
    return MysqlHelp.mysql

#执行命令
def execute(self,sql='',param=(),autoclose=False):
    cursor, conn = self.db.getconn()
    try:
        if param:
            cursor.execute(sql, param)
        else:
            cursor.execute(sql)
        conn.commit()
        if autoclose:
            self.close(cursor, conn)
    except Exception as e:
        pass
    return cursor, conn

#执行多条命令
'[{"sql":"xxx","param":"xx"}....]'
def executemany(self,list=[]):
    cursor,conn=self.db.getconn()
    try:
        for order in list:
            sql=order['sql']
            param=order['param']
            if param:
                cursor.execute(sql,param)
            else:
                cursor.execute(sql)
        conn.commit()
        self.close(cursor, conn)
        return True
    except Exception as e:
        print 'execute failed========',e.args
        conn.rollback()
        self.close(cursor, conn)
        return False
def connect(self):
    self.conn = MySQLdb.connect(user='root', db='asterisk', passwd='kalamodo', host='192.168.88.6')

def close(self,cursor,conn):
    cursor.close()
    conn.close()
    print u"PT连接池释放con和cursor";

传送门 http://download.csdn.net/download/u010939285/9831459

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python DBUtils 是一个轻量级的 Python 数据库连接池库,支持多个线程和多个进程,并可与各种数据库后端一起使用。DBUtils 是一个纯 Python 库,没有其他依赖项。 DBUtils 的主要目的是提供一个共享数据库连接池,这样可以避免在不同的线程和进程中频繁地打开和关闭数据库连接。这可以极大地提高应用程序的性能和响应速度。 DBUtils 提供了一些常见的数据库连接池实现,包括 PooledDB,PersistentDB 和 StackedObjectPool。这些实现都提供了相同的接口,因此可以很容易地将它们用于不同的应用程序。 使用 DBUtils 可以在保持代码简洁的同时获得数据库连接池的好处。以下是一个使用 DBUtils 连接 MySQL 数据库的示例: ```python import pymysql from dbutils.pooled_db import PooledDB POOL = PooledDB( creator=pymysql, maxconnections=5, mincached=2, maxcached=5, blocking=True, maxusage=None, host='localhost', port=3306, user='root', password='password', database='test', charset='utf8mb4' ) def get_conn(): return POOL.connection() def query_data(sql): conn = get_conn() cursor = conn.cursor() cursor.execute(sql) result = cursor.fetchall() cursor.close() conn.close() return result ``` 在上面的示例中,我们使用 `PooledDB` 创建了一个 MySQL 数据库连接池,并使用 `get_conn` 获取一个连接对象,然后使用 `query_data` 函数执行 SQL 查询。注意,我们在使用完连接后需要手动关闭连接。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值