Connection.__exit__ 是否在 sqlite3 中自行关闭?

Does Connection.__exit__ close itself in sqlite3?

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

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

我假设连接在从 with 块退出时自行关闭,就像文件一样,但现在我对此有些怀疑。我查看了 Connection class 文档,但没有找到任何线索。有人确切地知道 Connection.__exit__ 到底是做什么的吗?提前致谢!

不,它 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