I got a little program with my code below:
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!')
When the code reach the line with db.cursor() as c:, the program gives the following error
with db.cursor() as c: AttributeError: __exit__
What do I wrong?
1 Answer 1
The expression passed to the with statement (db.cursor()) in this case should return a context manager object. A context manager object must have both an __enter__and __exit__ method ( Under the hood, the with statement uses these the methods to ensure that the object is cleaned up correctly).
The sqlite3 cursor object doesn't implement these methods so it isn't a valid context manager method, hence the error message you're getting.
You could write your own context manager around cursor. You could write one yourself, but in most cases this isn't necessary, just assign db.cursor() to db directly
c = db.cursor()
withwith it.