Python 多源配置的一种方法

定义配置文件 config.py

class LocalDB:
    class Local1:
        info = {
            "Host": "127.0.0.1",
            "Port": "3306",
            "UserName": "root",
            "Password": "1122",
        }
        information_schema = "information_schema"
        mysql = "mysql"
        performance_schema = "performance_schema"
        sys = "sys"
        test = "test"

    class Local2:
        info = {
            "Host": "127.0.0.2",
            "Port": "3306",
            "UserName": "root",
            "Password": "1122",
        }
        information_schema = "information_schema"
        mysql = "mysql"
        performance_schema = "performance_schema"
        sys = "sys"
        test = "test"

封装pymysql

class DBConn(object):

    def __init__(self, db_setting, db_name):
        try:
            host = db_setting["Host"]
            port = db_setting["Port"]
            user_name = db_setting["UserName"]
            password = db_setting["Password"]
            self.engine = create_engine("mysql+pymysql://" + user_name + ":" + quote_plus(password) + "@" + host + ":" + port + "/" + db_name + "?charset=utf8")
            self.conn = pymysql.connect(host=host, port=int(port), user=user_name, password=password, database=db_name, charset="utf8", connect_timeout=180)
            self.cur = self.conn.cursor()
            session = sessionmaker(bind=self.engine)  # engine 是数据库连接对象
            self.session = session()
        except Exception as e:
            raise ConnectionError(f"数据库连接失败,{str(e)}")

    def __enter__(self):
        return self

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

    def close(self):
        self.engine.dispose()
        self.cur.close()
        self.conn.close()
        self.session.close()

    def fetchone(self, sql):
        self.cur.execute(sql)
        data = self.cur.fetchone()
        return data

    def fetchall(self, sql):
        self.cur.execute(sql)
        data = self.cur.fetchall()
        return data

    def get_columns(self):
        return [i[0] for i in self.cur.description]

使用示例

with DBConn(LocalDB.Local1.info, LocalDB.Local1.test) as local1_db:
    sql = "show tables;"
    for table_name in local1_db.fetchall(sql):
        print(table_name[0])

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值