gpt4 book ai didi

python - 无法删除sqlite数据库

转载 作者:可可西里 更新时间:2023-11-01 11:55:12 25 4
gpt4 key购买 nike

如果我执行包含以下内容的脚本,然后尝试删除文件系统上的 mydb,我将无法执行此操作,直到我关闭 python idle。这里有什么问题?

   with sqlite3.connect(r'./mydb') as connection:
cursor = connection.cursor()
cursor.executemany('...' )
connection.commit()

最佳答案

sqlite 连接上下文管理器管理事务,而不是连接。 __exit__ 处理程序提交或回滚,它不会关闭连接。参见 Using the connection as a context manager :

Connection objects can be used as context managers that automatically commit or rollback transactions. In the event of an exception, the transaction is rolled back; otherwise, the transaction is committed.

您必须自己明确关闭连接,或使用 contextlib.closing context manager :

from contextlib import closing

with closing(sqlite3.connect(r'./mydb')) as connection:
with connection:
cursor = connection.cursor()
cursor.executemany('...' )

关于python - 无法删除sqlite数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18999988/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com