Python MySQL 和上下文管理器 : __exit__ Attribute error

标签 python mysql python-2.7 contextmanager

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

最佳答案

只需使用 with MySQLCursor() as cursor: - With 语句需要具有 __enter____exit__ 方法的类的实例,而不是类本身。

关于Python MySQL 和上下文管理器 : __exit__ Attribute error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40994574/

相关文章:

python - 当类有描述符时 __str__ 遇到 RecursionError

python - 大 O 表示法 - python 函数

mysql - 仅对原始查询使用 sequelize

php - 防止Mysql覆盖数据

python - 如何使用Python查找文件中的特殊单词?

python - 将此文件转换成字典

python - aiohttp - 设置 cookie 然后重定向用户

python - `tf.reciprocal` 与 `tf.inv` : is there any difference?

PHP MySQL 混淆

python-2.7 - python中的模糊匹配日语字符串?