Python MySQL和上下文管理器:_退出_属性错误

Python MySQL和上下文管理器:_退出_属性错误,python,mysql,python-2.7,contextmanager,Python,Mysql,Python 2.7,Contextmanager,使用Python2.7.9,我试图计算mysql连接和游标的打开和关闭 代码是 class MySQLCursor: def __init__(self, commit=False): self.commit = commit def __enter__(self): self.conn = MySQLdb.connect(host=_MYMYSQLHOST, user=_M

使用Python2.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问题还是上下文管理器问题?

只需使用MySQLCursor()作为游标执行
-with语句需要使用
\uuuuuuuuuuuuuuuuu
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu>方法的类实例,而不是类本身。

尝试使用MySQLCursor()作为游标