开发者

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

开发者 https://www.devze.com 2022-12-15 16:05 出处:网络
Let\'s say that you have the following开发者_开发技巧 code: import sqlite3 conn = sqlite3.connect(\'mydb\')

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

精彩评论

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