3

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
  • 2
    The cursor doesn't support a context manager. You cant use with with it. Commented Jan 19, 2017 at 10:35

1 Answer 1

8

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.