Python MySQL 和上下文管理器:__exit__ 属性错误
Python MySQL and context managers: __exit__ Attribute error
使用 Python 2.7.9,我试图分解 mysql 连接和游标的打开和关闭
密码是
class MySQLCursor:
def __init__(self, commit=False):
self.commit = commit
def __enter__(self):
self.conn = MySQLdb.connect(host=_MYMYSQLHOST,
user=_MYMYSQLUSER,
passwd=_MYMYSQLPASSWD,
db=_MYMYSQLDB)
self.cursor = self.conn.cursor()
return self.cursor
def __exit__(self, exc_type, exc_val, exc_tb):
if self.commit:
self.conn.commit()
self.cursor.close()
self.conn.close()
return
用作
with MySQLCursor as cursor:
cursor.execute("SELECT VERSION()")
row = cursor.fetchone()
print "server version:", row[0]
我收到错误消息
AttributeError: __exit__
这是 mysql 问题还是上下文管理器问题?
Just do with MySQLCursor() as cursor:
- With 语句需要具有 __enter__
和 __exit__
方法的 类 实例,而不是 类 本身。
使用 Python 2.7.9,我试图分解 mysql 连接和游标的打开和关闭
密码是
class MySQLCursor:
def __init__(self, commit=False):
self.commit = commit
def __enter__(self):
self.conn = MySQLdb.connect(host=_MYMYSQLHOST,
user=_MYMYSQLUSER,
passwd=_MYMYSQLPASSWD,
db=_MYMYSQLDB)
self.cursor = self.conn.cursor()
return self.cursor
def __exit__(self, exc_type, exc_val, exc_tb):
if self.commit:
self.conn.commit()
self.cursor.close()
self.conn.close()
return
用作
with MySQLCursor as cursor:
cursor.execute("SELECT VERSION()")
row = cursor.fetchone()
print "server version:", row[0]
我收到错误消息
AttributeError: __exit__
这是 mysql 问题还是上下文管理器问题?
Just do with MySQLCursor() as cursor:
- With 语句需要具有 __enter__
和 __exit__
方法的 类 实例,而不是 类 本身。