views:

313

answers:

2

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.

A: 

You could wrap in a try, except statement:

>>> conn = sqlite3.connect('test')
>>> conn.close()
>>> try:
...   resultset = conn.execute("select 1 from mytable;")
... except sqlite3.ProgrammingError, err:
...   print err
Cannot operate on a closed database.

This relies on a shortcut specific to sqlite3.

Adam Bernier
The method is sane, but avoid doing a `SELECT * FROM mytable` while you can do a much lighter `SELECT one_column FROM mytable LIMIT 1`. The former is horribly inefficient is you have a non-small database.
Antoine P.
thanks @pitrou, updated to take that into consideration.
Adam Bernier
A: 

How about making sure that the connection and cursor are never closed?

You could have a state based program that you can guarantee only calls close() at the right time.

Or wrap them in other objects that have a pass implementation of close(). Or add an _isclosed member set by close() and accessed by isclosed().

quamrana