1.3 pymysql 单例模式

import pymysql
from dbutils.pooled_db import PooledDB
import threading

POOL = PooledDB(
    creator=pymysql,  # 使用链接数据库的模块
    maxconnections=6,  # 连接池允许的最大连接数,0和None表示不限制连接数
    mincached=2,  # 初始化时,链接池中至少创建的链接,0表示不创建
    blocking=True,  # 连接池中如果没有可用连接后,是否阻塞等待。True,等待;False,不等待然后报错
    ping=0,
    # 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
    host='home.vimll.com',
    port=xxxx,
    user='python',
    password='xxxxx',
    database='test',
    charset='utf8'
)

class SqlHelper(object):
    def __init__(self):
        self.conn = None
        self.cursor = None

    def open(self):
        conn = POOL.connection()
        cursor = conn.cursor()
        return conn, cursor

    def close(self):
        self.cursor.close()
        self.conn.close()

    def fetchall(self, sql, *args):
        """ 获取所有数据 """
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchall()
        self.close(conn, cursor)
        return result

    def fetchone(self, sql, *args):
        """ 获取一条数据 """
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchone()
        self.close(conn, cursor)
        return result

    def fetchmany(self, sql, *args, num=1):
        """ 获取指定多少条数据 """
        conn, cursor = self.open()
        cursor.execute(sql, args)
        result = cursor.fetchmany(size=num)
        self.close(conn, cursor)
        return result

    def __enter__(self):
        self.conn, self.cursor = self.open()
        return self.cursor

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()

if __name__ == '__main__':
    db = SqlHelper()

    with db as cur:
        cur.execute('select * from `order` where order_id=%s;', '1')
        with db as cur2:
            cur2.execute('select * from `order` where order_id=%s;', '2')

            result = cur.fetchone()
            result2 = cur2.fetchone()
            print(result, result2)

    with SqlHelper() as cur:
        cur.execute('select * from `order`;')
        result = cur.fetchall()
        print(result)