我有一个小程序,代码如下:
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!')
Run Code Online (Sandbox Code Playgroud)
当代码到达 db.cursor() as c: 的行时,程序给出以下错误
Run Code Online (Sandbox Code Playgroud)with db.cursor() as c: AttributeError: __exit__
我有什么错吗?
with在这种情况下,传递给语句 ( )的表达式db.cursor()应返回一个上下文管理器对象。上下文管理器对象必须具有 and__enter__方法__exit__(在幕后,该with语句使用这些方法来确保正确清理对象)。
sqlite3 游标对象没有实现这些方法,因此它不是有效的上下文管理器方法,因此您会收到错误消息。
您可以围绕光标编写自己的上下文管理器。你可以自己写一个,但大多数情况下这不是必需的,只需将 db.cursor() 直接分配给 db
c = db.cursor()
Run Code Online (Sandbox Code Playgroud)