0
点赞
收藏
分享

微信扫一扫

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


环境:

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)​​




举报

相关推荐

0 条评论