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.
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.
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."
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.
Yes, we should close our cursor.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With