开发者

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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜