您当前的位置: 首页 >  彭世瑜 Python

Python编程:利用上下文管理器管理MySQL的链接对象

彭世瑜 发布时间:2019-03-28 17:25:15 ,浏览量:1

环境: python 2.7.5

代码示例

# -*- coding: utf-8 -*-


import MySQLdb


class DataBase(object):
    def __init__(self, hostname, username, password, database, port, charset='utf-8'):
        self.conn = MySQLdb.Connect(
            host=hostname,
            user=username,
            passwd=password,
            db=database,
            port=port,
            charset=charset,
            autocommit=True
        )
        self.cursor = self.conn.cursor()

    def __enter__(self):
        return self.cursor

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

参数解释

exc_type : Type 异常类型
exc_val : Value 异常值
exc_tb : TreacBack 异常回溯追踪

由于线上环境使用的是 MySQL-python 1.2.5 所以没有用pymysql,替换模块之后使用方式也一样的

参考

  1. with与“上下文管理器”,以及其在数据库上的应用
  2. python黑魔法—上下文管理器(contextor)
关注
打赏
1688896170
查看更多评论

彭世瑜

暂无认证

  • 1浏览

    0关注

    2727博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文
立即登录/注册

微信扫码登录

0.0552s