美文网首页
python 上下文管理 / mysql 连接

python 上下文管理 / mysql 连接

作者: 智勇双全的小六 | 来源:发表于2018-04-04 13:50 被阅读0次

    连接设计

    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 连接

          本文链接:https://www.haomeiwen.com/subject/unukhftx.html