假设您有以下代码:
import sqlite3 conn = sqlite3.connect('mydb') cur = conn.cursor() # some database actions cur.close() conn.close() # more code below
如果我稍后尝试使用conn
或cur
对象,我怎么能告诉它们已关闭?我找不到.isclosed()
方法或类似的东西.
你可以在try, except
声明中包装:
>>> conn = sqlite3.connect('mydb') >>> conn.close() >>> try: ... resultset = conn.execute("SELECT 1 FROM my_table LIMIT 1;") ... except sqlite3.ProgrammingError as e: ... print e Cannot operate on a closed database.
这依赖于特定于sqlite3的快捷方式.