Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to tell if Python SQLite database connection or cursor is closed?

Let's say that you have the following code:

import sqlite3

conn = sqlite3.connect('mydb')
cur = conn.cursor()
# some database actions
cur.close()
conn.close()
# more code below

If I try to use the conn or cur objects later on, how could I tell that they are closed? I cannot find a .isclosed() method or anything like it.

like image 841
daveslab Avatar asked Dec 30 '09 17:12

daveslab


People also ask

How can I tell if a SQLite database is open?

To see if it's opened, check the pointer to see if it's NULL (which you of course must initialize it to, or else it has an unspecified value). After you close it, assign it to NULL again, and there's your "is open" flag. By the way, creating a DatabaseHandle class using RAII is strongly suggested.

How do I close SQLite connection in Python?

there are two ways a connection is closed: either you call . close() explicitly after which you still have a handle but can't use it, or you let the connection go out of scope and get garbage-collected. if you must close a connection, close it explicitly, according to Python's motto "explicit is better than implicit."

How do I close a SQLite database connection?

close( conn ) closes the SQLite connection by using the MATLAB® interface to SQLite. The SQLite connection object remains open until you close it using the close function. Always close this object when you finish using it.

Is it necessary to close a cursor in Python?

Yes, we should close our cursor.


1 Answers

You could wrap in a try, except statement:

>>> conn = sqlite3.connect('mydb')
>>> conn.close()
>>> try:
...     one_row = conn.execute("SELECT * FROM my_table LIMIT 1;")
... except sqlite3.ProgrammingError as e:
...     print(e)
Cannot operate on a closed database.

This relies on a shortcut specific to sqlite3.

like image 162
mechanical_meat Avatar answered Oct 04 '22 23:10

mechanical_meat