问题描述
我正在做这样的事情...
I am doing something like this...
conn = sqlite3.connect(db_filename)
with conn:
cur = conn.cursor()
cur.execute( ... )
with
自动提交更改.但是文档没有说关闭连接.
with
automatically commits the changes. But the docs say nothing about closing the connection.
实际上我可以在后面的语句(我已经测试过)中使用 conn
.因此,上下文管理器似乎没有关闭连接.
Actually I can use conn
in later statements (which I have tested). Hence it seems that the context manager is not closing the connection.
我必须手动关闭连接吗?如果我让它保持打开状态怎么办?
Do I have to manually close the connection. What if I leave it open?
编辑
我的发现:
- 上下文管理器中的连接未关闭,我已经测试并确认了.在
__exit__
时,上下文管理器仅通过执行conn.commit()
来提交更改 with conn
和with sqlite3.connect(db_filename) as conn
是一样的,所以使用任一个仍然会保持连接处于活动状态with
语句不会创建新的作用域,因此在 with 套件内部创建的所有变量都可以在它外部访问- 最后,您应该手动关闭连接
- The connection is not closed in the context manager, I have tested and confirmed it. Upon
__exit__
, the context manager only commits the changes by doingconn.commit()
with conn
andwith sqlite3.connect(db_filename) as conn
are same, so using either will still keep the connection alivewith
statement does not create a new scope, hence all the variables created inside the suite of with will be accessible outside it- Finally, you should close the connection manually
推荐答案
在回答不关闭 SQLite 数据库会发生什么的具体问题时,答案非常简单,适用于在任何编程语言中使用 SQLite.当连接被代码显式关闭或程序退出隐式关闭时,任何未完成的事务都会回滚.(回滚实际上是由下一个打开数据库的程序完成的.)如果没有未完成的事务打开,那么什么都不会发生.
In answer to the specific question of what happens if you do not close a SQLite database, the answer is quite simple and applies to using SQLite in any programming language. When the connection is closed explicitly by code or implicitly by program exit then any outstanding transaction is rolled back. (The rollback is actually done by the next program to open the database.) If there is no outstanding transaction open then nothing happens.
这意味着您不必太担心在进程退出之前总是关闭数据库,并且您应该注意确保启动它们并在适当的点提交的事务.
This means you do not need to worry too much about always closing the database before process exit, and that you should pay attention to transactions making sure to start them and commit at appropriate points.
这篇关于如果我不关闭 Python SQLite 中的数据库连接怎么办的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!