仅原文翻译以及一些个人理解

参数解释

在这里插入图片描述

  1. creator:数据库驱动模块,如常见的pymysql,pymssql,cx_Oracle模块。无默认值
  2. mincached:初始化连接池时创建的连接数。默认为0,即初始化时不创建连接。(建议默认0,假如非0的话,在某些数据库不可用时,整个项目会启动不了)
  3. maxcached:池中空闲连接的最大数量。默认为0,即无最大数量限制。(建议默认)
  4. maxshared:池中共享连接的最大数量。默认为0,即每个连接都是专用的,不可共享(不常用,建议默认)
  5. maxconnections:被允许的最大连接数。默认为0,无最大数量限制。(视情况而定)
  6. blocking:连接数达到最大时,新连接是否可阻塞。默认False,即达到最大连接数时,再取新连接将会报错。(建议True,达到最大连接数时,新连接阻塞,等待连接数减少再连接)
  7. maxusage:连接的最大使用次数。默认0,即无使用次数限制。(建议默认)
  8. setsession:可选的SQL命令列表,可用于准备会话。(例如设置时区)
  9. reset:当连接返回到池中时,重置连接的方式。默认True,总是执行回滚。(不太清楚,建议默认)
  10. ping:确定何时使用ping()检查连接。默认1,即当连接被取走,做一次ping操作。0是从不ping,1是默认,2是当该连接创建游标时ping,4是执行sql语句时ping,7是总是ping
连接常见数据库
import importlib
from DBUtils.PooledDB import PooledDB


class DataBase(object):

    def __init__(self, db_type, config):

        self.__db_type = db_type

        if self.__db_type == 'mysql':
            db_creator = importlib.import_module('pymysql')
        elif self.__db_type == 'sqlserver':
            db_creator = importlib.import_module('pymssql')
        elif self.__db_type == 'oracle':
            db_creator = importlib.import_module('cx_Oracle')
        else:
            raise Exception('unsupported database type ' + self.__db_type)
        self.pool = PooledDB(
            creator=db_creator,
            mincached=0,
            maxcached=6,
            maxconnections=0,
            blocking=True,
            ping=0,
            **config
        )

    def execute_query(self, sql, as_dict=True):
    	"""
        查询语句
        :param sql: 
        :param as_dict: 
        :return: 
        """
        conn = None
        cur = None
        try:
            conn = self.pool.connection()
            cur = conn.cursor()
            cur.execute(sql)
            rst = cur.fetchall()
            if rst:
                if as_dict:
                    fields = [tup[0] for tup in cur._cursor.description]
                    return [dict(zip(fields, row)) for row in rst]
                return rst
            return rst

        except Exception as e:
            print('sql:[{}]meet error'.format(sql))
            print(e.args[-1])
            return ()
        finally:
            if conn:
                conn.close()
            if cur:
                cur.close()
                
    def execute_manay(self, sql, data):
        """
        执行多条语句
        :param sql:
        :param data:
        :return:
        """
        conn = None
        cur = None
        try:
            conn = self.pool.connection()
            cur = conn.cursor()
            cur.executemany(sql, data)
            conn.commit()
            return True
        except Exception as e:
            print('[{}]meet error'.format(sql))
            print(e.args[-1])
            conn.rollback()
            return False
        finally:
            if conn:
                conn.close()
            if cur:
                cur.close()


MySQL = DataBase(
    'mysql', {'user': 'sa', 'host': '127.0.0.1', 'password': 'xxxx', 'database': 'test', 'port': 3306}
)
MsSQL = DataBase(
    'sqlserver', {'user': 'sa', 'host': '127.0.0.1', 'password': 'xxxxx', 'database': 'test', 'port':1433}
)
Oracle = DataBase(
    'oracle', {'user': 'sa', 'dsn': '127.0.0.1:1903/google', 'password': 'xxxxxx', 'encoding': 'utf-8'}
)

连接oracle时,必须指定encoding,否则会报错’ordinal not in range(128)’。python3连接oracle失败的话,可以参考这篇文章https://blog.csdn.net/diuleilaomu/article/details/97487065

Logo

更多推荐