如果我不关闭 Python SQLite 中的数据库连接怎么办 [英] What if I don't close the database connection in Python SQLite

查看:48
本文介绍了如果我不关闭 Python SQLite 中的数据库连接怎么办的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做这样的事情...

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 connwith 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 doing conn.commit()
  • with conn and with sqlite3.connect(db_filename) as conn are same, so using either will still keep the connection alive
  • with 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 中的数据库连接怎么办的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆