【问题标题】:Python database sqlite3Python 数据库 sqlite3
【发布时间】:2017-01-19 19:14:56
【问题描述】:

我的代码如下:

def get_code(hex_pattern, database='./AndroidLockScreenRainbow.sqlite'):
    try:
        if os.path.exists(database):
            with lite.connect(database) as db:
                with db.cursor() as c:
                    c.execute("SELECT * FROM RainbowTable")
                    rows = c.fetchall()
                    for row in rows:
                        if row[0] == hex_pattern:
                            return row[1]
        else:
            raise lite.OperationalError("Database file not exists")
    except lite.OperationalError:
        print('Given SQL table not found!')

当代码到达 db.cursor() as c: 的行时,程序给出以下错误

with db.cursor() as c:
AttributeError: __exit__

我做错了什么?

【问题讨论】:

  • 游标不支持上下文管理器。你不能和它一起使用with

标签: python sqlite


【解决方案1】:

在这种情况下,传递给with 语句 (db.cursor()) 的表达式应该返回一个上下文管理器对象。上下文管理器对象必须同时具有__enter____exit__ 方法(在后台,with 语句使用这些方法来确保正确清理对象)。

sqlite3 游标对象没有实现这些方法,因此它不是有效的上下文管理器方法,因此您会收到错误消息。

您可以围绕光标编写自己的上下文管理器。你可以自己写一个,但在大多数情况下这不是必需的,只需将 db.cursor() 直接分配给 db

c = db.cursor()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-08
    相关资源
    最近更新 更多