Python 数据库 sqlite3

3
我有一个小程序,代码如下:
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()的那一行时,程序会出现以下错误。
with db.cursor() as c:
AttributeError: __exit__
我应该怎样做才能正确呢?

2
光标不支持上下文管理器。您不能在其上使用 with - Paul Rooney
1个回答

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

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

您可以编写自己的游标上下文管理器。但在大多数情况下,这并不是必需的,只需直接将db.cursor()分配给db即可。
c = db.cursor()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接