14

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.

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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.
@AntoineP. you are confusing SQLite with other databases. There is no difference in the amount of work done by SQLite. It does not calculate all the results for a query upfront - instead it does the least amount of work possible to give the first result row. The second result row is only worked out when you ask for it. Consequently the limit has no effect. In any event a better query is one that doesn't depend on the schema - eg PRAGMA user_version.
0

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().

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.