python 上下文管理 / mysql 连接

连接设计

import pymysql
from utils.parse_json import Jackson
from config.config_file_path import FilePath
from pymysql.util import byte2int


class DB:
    def __init__(self, which_db="testMetaDB", config_file=FilePath.db_config):
        self.source = Jackson.parse_json_file(config_file)[which_db]
        self.conn = pymysql.connect(host=self.source["host"], port=self.source["port"], user=self.source["user"],
                                    password=self.source["password"],
                                    database=self.source["database"], charset="utf8", connect_timeout=10)
        self.cursor = self.conn.cursor()

    def __enter__(self):
        return self

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

    def execute(self, sql: str, args=None):
        self.cursor.execute(sql, args)
        self.conn.commit()

    def executemany(self, sql: str, data: list):
        self.cursor.executemany(sql, data)
        self.conn.commit()

    def fetch_one(self, sql: str, args=None):
        self.cursor.execute(sql, args)
        return self.cursor.fetchone()

    def fetch_all(self, sql: str, args=None):
        self.cursor.execute(sql, args)
        return self.cursor.fetchall()

使用

sql = "select ...."
        with DB() as db:
            return db.fetch_all(sql)

使用 with 的这种方式真爽啊

你可能感兴趣的:(python 上下文管理 / mysql 连接)