我正在编写一些连接到 sqlite 数据库的代码。在调试上述代码的过程中,我遇到了挂起与数据库的打开连接的问题,因为某些错误阻止了关闭命令的执行。因为 db 和 c 是在一个函数中定义的,所以我无法从命令行找到并关闭这些对象。它们就像孤立的连接或其他东西,但无论如何它们会阻止我对数据库做任何其他事情,直到我关闭并重新打开我的交互式控制台。这是它的样子:
def something()
db=sqlite3.connect('mydatabase')
c=db.cursor()
somecode
lots of different things happening in here
this may have errors
thus stopping execution
db.commit()
c.close()
db.close()
我已经在“finally” block 中尝试了一个带有最终关闭操作的 try/except 子句,但这可以防止在我调试时将异常返回到交互式输出,并且事情“无声地”失败(也许我我没有做那部分吗?)。有更好的方法吗?
最佳答案
通常最好使用 with...as 语句:
with sqlite.connect(...) as db:
with db.cursor() as c:
...
with 语句保证在 with 语句结束或引发异常时对对象调用 close()。甚至当从内部调用 return 或 yield 时。
在这里阅读更多: http://docs.python.org/2/reference/compound_stmts.html#with
关于python - 如何确保在调试期间关闭 sqlite 数据库连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15551323/