基于pymysql封装一个使用上下文管理器和连接装饰器的数据库操作模块

import pymysql
from dbutils.pooled_db import PooledDB


class MysqlPool:
    config = {
        'creator': pymysql,
        'host': "***.***.***.***",
        'port': 3306,
        'user': 'root',
        'password': '***',
        'db': 'old_boy_python',
        'charset': "utf8",
        'maxconnections': 70,  # 连接池最大连接数量
        'cursorclass': pymysql.cursors.DictCursor
    }
    pool = PooledDB(**config)

    def __enter__(self):
        self.conn = MysqlPool.pool.connection()
        self.cursor = self.conn.cursor()
        return self

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


def db_conn(func):
    def wrapper(*args, **kwargs):
        with MysqlPool() as db:
            result = func(db, *args, **kwargs)
        return result

    return wrapper


class DoMysql:
    @staticmethod
    @db_conn
    def select_one_data(db, p_sql):
        db.conn.commit()
        db.cursor.execute(p_sql)
        return db.cursor.fetchone()

    @staticmethod
    @db_conn
    def select_all_data(db, p_sql):
        db.conn.commit()
        db.cursor.execute(p_sql)
        return db.cursor.fetchall()

    @staticmethod
    @db_conn
    def get_count(db, p_sql):
        db.conn.commit()
        return db.cursor.execute(p_sql)

    @staticmethod
    @db_conn
    def update(db, p_sql):
        """
        对数据库进行增、删、改的操作。
        :param db:
        :param p_sql:
        :return:
        """
        db.cursor.execute(p_sql)
        db.conn.commit()


sql = DoMysql()

if __name__ == '__main__':
    sql.update("UPDATE PaginationPractice_book SET price='33' WHERE id='1';")
    res = sql.select_all_data("SELECT * FROM PaginationPractice_book;")
    print(res)

你可能感兴趣的:(python测试开发,数据库,mysql,python)