sqlite3.ProgrammingError: Cannot operate on a closed database. [Python] [sqlite] sqlite3.ProgrammingError: Cannot operate on a closed database. [Python] [sqlite] sqlite sqlite

sqlite3.ProgrammingError: Cannot operate on a closed database. [Python] [sqlite]


You write "It seems to me like the connection to the database is not closed before the second connection is attempted" but, in fact, there is no "second connection" to the database. You're using a single connection, which I'm guessing is created in the initializer (__init__) for the not-shown-in-your-example class that contains the method execute_query.

You (again guessing) create the conn in that __init__ method, but you close it immediately after executing any query. Therefore, it will not be available when you execute another query.

Instead, you should not .close() but rather .commit() at the end of your query. Don't do this in finally but rather at the end of the try. That way the transaction will either be committed (if it succeeds) or rolled back (in the except block, if it fails).

Then, add a separate .close() method to your larger class which in turn calls .close() on the connection, and have the calling program call that method when it's finished with all its queries. That call to close would appropriately appear in a finally block inside the larger program.


Remove this from code

 self.conn.close()

It will resolve the problem because when you want to retrieve information from database you cannot write

conn.close()


Why is a business method closing the connection? Surely it should close the cursor instead? Closing the connection would mean that the second time the executeQuery is called, it would fail because the connection is gone.