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

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

问题描述

我正在这样做...

  conn = sqlite3.connect(db_filename)

with conn:
cur = conn.cursor()
cur.execute(...)

自动提交更改。但是文档什么也不说关闭连接。



实际上,我可以在以后的语句(我测试过)中使用 conn 。因此,上下文管理器似乎没有关闭连接。



我必须手动关闭连接。



我的结论...




  • 在上下文管理器中的连接未关闭,我已测试并确认。在 __ exit __ ,上下文管理器只通过执行 conn.commit()

  • 与conn 与sqlite3.connect(db_filename)as conn 东西。因此,使用任何一个将仍然保持连接生效

  • 语句不创建一个新的范围,



<解决方案

在回答关于如果你不关闭SQLite数据库会发生什么的具体问题,答案很简单,适用于在任何编程语言中使用SQLite。当连接由代码显式关闭或程序退出隐式关闭时,任何未完成的事务将回滚。 (回滚实际上是由下一个程序打开数据库。)如果没有未完成的事务打开,则什么也不会发生。



这意味着你不需要担心太多关于在进程退出之前总是关闭数据库,并且您应该注意事务,确保启动它们并在适当的点提交。


I am doing something like this...

conn = sqlite3.connect(db_filename)

with conn:
    cur = conn.cursor()
    cur.execute( ... )

with automatically commits the changes. But the docs say nothing about closing the connection.

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?

EDIT

My conclusions...

  • 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 one and the same thing. 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

解决方案

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天全站免登陆