【问题标题】:Does Connection.__exit__ close itself in sqlite3?Connection.__exit__ 是否在 sqlite3 中自行关闭?
【发布时间】:2019-10-20 08:24:20
【问题描述】:
我使用with 语句打开 SQL 连接,像这样
with sqlite3.connect('data.db') as con:
# do something here
我认为连接在退出 with 块时会自行关闭,就像文件一样,但现在我对此有些怀疑。我查看了Connection class 文档,但没有找到任何线索。有人确切知道Connection.__exit__ 的作用吗?提前致谢!
【问题讨论】:
标签:
python
sqlite
with-statement
【解决方案1】:
不,它doesn't close the connection:
# Connection object used as context manager only commits or rollbacks transactions,
# so the connection object should be closed manually
con.close()
将连接用作上下文管理器将提交或回滚。
如果您也想自动关闭,您可以使用contextlib.closing 上下文管理器:
from contextlib import closing
with closing(sqlite3.connect('data.db')) as con:
with con:
# do something here
你需要第二个with。