【发布时间】:2020-02-26 01:35:12
【问题描述】:
我在 Python 中使用 tempfile 和 sqlite3 模块。
以下代码有效:
import sqlite3, tempfile
conn1 = sqlite3.connect(tempfile.TemporaryFile().name)
因此,我希望以下代码也能正常工作,但事实并非如此:
import sqlite3, tempfile
database_file = tempfile.TemporaryFile()
conn2 = sqlite3.connect(database_file.name)
sqlite3.OperationalError: 无法打开数据库文件
我能够使用this answer 来提取 conn1 使用的文件路径。将其输入 sqlite.connect 也可以:
import sqlite3, tempfile
conn1 = sqlite3.connect(tempfile.TemporaryFile().name)
cur = conn1.cursor()
cur.execute("PRAGMA database_list")
row = cur.fetchone()
database_file_path = row[2]
conn3 = sqlite3.connect(database_file_path)
看来我可以使用 TemporaryFile().name,只要我不将它保存在变量中。这是有问题的,因为在我的真实代码中我需要存储临时文件的路径。我可以通过使用用于生成 conn3 的代码来解决所有这些问题,但是似乎无缘无故地创建额外的数据库连接和 SQL 查询是非常丑陋和低效的。
【问题讨论】:
-
将函数结果分配给变量并将其作为参数传递与直接传递函数结果没有区别。一定是发生了其他事情。
-
你应该使用
NamedTemporaryFile。 -
@Barmar 感谢您的建议,但不幸的是,这似乎也不起作用。我在答案中运行了第二个代码块,将 TemporaryFile 替换为 NamedTemporary File。我得到了和以前一样的错误。
标签: python sql python-3.x sqlite temporary-files