我曾经使用with
语句来打开SQL连接,像这样
with sqlite3.connect('data.db') as con:
# do something here
我以为连接在with
块的退出时会关闭,就像文件一样,但是现在我对此有些怀疑。我浏览了Connection class文档,但没有发现任何线索。有人确定Connection.__exit__
到底是做什么的吗?预先感谢!
答案 0 :(得分: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
。