Connection .__ exit__是否在sqlite3中关闭自身?

时间:2019-10-20 08:24:20

标签: python sqlite with-statement

我曾经使用with语句来打开SQL连接,像这样

with sqlite3.connect('data.db') as con:
    # do something here

我以为连接在with块的退出时会关闭,就像文件一样,但是现在我对此有些怀疑。我浏览了Connection class文档,但没有发现任何线索。有人确定Connection.__exit__到底是做什么的吗?预先感谢!

1 个答案:

答案 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

相关问题