1

一,使用contextmanager

from contextlib import contextmanager
import MySQLdb

DB_CONFIG = {
    'host': '192.168.1.253',
    'user': 'pythondb',
    'passwd': 'python123',
    'port': 20002,
    'db': 'xw',
    'charset': 'utf8'
}


@contextmanager
def open_mysql(db_conf):
    try:
        conn = MySQLdb.connect(**db_conf)
        if conn:
            yield conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
    except Exception as e:
        print(e)
    finally:
        conn.close()

if __name__ == '__main__':
    with open_mysql(DB_CONFIG) as con:
        sql = 'select 1 as c'
        con.execute(sql)
        rv = con.fetchall()
        print(rv)

二,使用__enter__跟__exit__

class OpenMysqlConn(object):
    def __init__(self, db_conf):
        self.db_conf = db_conf
        self.conn = None

    def __enter__(self):
        try:
            self.conn = MySQLdb.connect(**self.db_conf)
            if self.conn:
                return self.conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
        except (AttributeError, MySQLdb.OperationalError):
            current_app.logger.error("连接数据库失败")

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

icheeringsoul
48 声望6 粉丝