我有一个小程序,下面是我的代码:
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!')当代码以c:的形式使用db.cursor()到达行时,程序会出现以下错误
使用db.cursor()作为c: AttributeError:__exit__
我做错什么了?
发布于 2017-01-19 10:36:07
在这种情况下,传递给with语句(db.cursor())的表达式应该返回上下文管理器对象。上下文管理器对象必须同时具有__enter__和__exit__方法( with语句使用这些方法来确保正确清理对象)。
sqlite3游标对象没有实现这些方法,因此它不是一个有效的上下文管理器方法,因此得到了错误消息。
您可以围绕游标编写自己的上下文管理器。您可以自己编写一个,但在大多数情况下这是不必要的,只需将db.cursor()直接分配给db即可
c = db.cursor()https://stackoverflow.com/questions/41739167
复制相似问题