import pymysql
from dbutils.pooled_db import PooledDB

pool = PooledDB(
    creator=pymysql,
    # 连接池允许的最大链接数，0和None表示不限制连接数
    maxconnections=6,
    # 初始化时，连接池中最少创建的空闲链接，0表示不创建
    mincached=2,
    # 连接池中最多闲置的链接，0和None表示不限制连接数
    maxcached=5,
    # 链接池中最多的共享链接数量，0和None表示全部共享，
    # PS: 无用，因为pymysql和MySQLdb等模块的 threadsafety都为1，所有值无论设置为多少，_maxcached永远为0，所以永远是所有链接都共享。
    maxshared=0,
    # 连接池中如果没有可用的链接后，是否阻塞等待。True：等待；False：不等待然后报错。
    blocking=True,
    # 一个链接最多被重复使用的次数，None表示无限制
    maxusage=None,
    # 开始会话前执行的命令列表，如：["set datestyle to ...", "set time zone ..."]
    setsession=[],
    # ping MySQL服务端，检查是否服务可用。# 如：0 = None = never, 1 = default = whenever it is requested,
    # 2 = when a cursor is created, 4 = when a query is executed, 7 = always
    ping=0,
    # 数据库ip
    host='127.0.0.1',
    port=3306,
    user='root',
    password='123456',
    database='autotest',
    charset='utf8'
)


class SQLHelper(object):
    @staticmethod
    def open():
        connection = pool.connection()
        cursor = connection.cursor(cursor=pymysql.cursors.DictCursor)
        return connection, cursor

    @staticmethod
    def close(connection, cursor):
        connection.commit()
        cursor.close()
        connection.close()

    @classmethod
    def fetch_one(cls, sql, args):
        conn, cursor = cls.open()
        cursor.execute(sql, args)
        obj = cursor.fetchone()
        cls.close(conn, cursor)
        return obj

    @classmethod
    def fetch_all(cls, sql, args):
        conn, cursor = cls.open()
        cursor.execute(sql, args)
        obj = cursor.fetchall()
        cls.close(conn, cursor)
        return obj

    @classmethod
    def fetch_many(cls, sql, args, num):
        conn, cursor = cls.open()
        cursor.execute(sql, args)
        obj = cursor.fetchmany(num)
        cls.close(conn, cursor)
        return obj

    @classmethod
    def insert_one(cls, sql, args):
        conn, cursor = cls.open()
        cursor.execute(sql, args)
        cls.close(conn, cursor)

    @classmethod
    def update_one(cls, sql, args):
        conn, cursor = cls.open()
        cursor.execute(sql, args)
        cls.close(conn, cursor)
