如何判断 Python SQLite 数据库连接或游标是否已关闭?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1981392/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to tell if Python SQLite database connection or cursor is closed?
提问by daveslab
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.
如果我稍后尝试使用conn
或cur
对象,我怎么知道它们已关闭?我找不到.isclosed()
方法或类似的东西。
采纳答案by mechanical_meat
You could wrap in a try, except
statement:
你可以用一个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.
This relies on a shortcut specific to sqlite3.
这依赖于特定于 sqlite3的快捷方式。
回答by quamrana
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.
你可以有一个基于状态的程序,你可以保证只在正确的时间调用 close() 。
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()
.
或者将它们包装在具有传递实现的其他对象中close()
。或添加由_isclosed
设置close()
和访问的成员isclosed()
。