python使用上下文处理器来管理mysql连接

发布时间:2019-08-05 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了python使用上下文处理器来管理mysql连接脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

一,使用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()

脚本宝典总结

以上是脚本宝典为你收集整理的python使用上下文处理器来管理mysql连接全部内容,希望文章能够帮你解决python使用上下文处理器来管理mysql连接所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。