的SQLite 需要数据库文件存储在磁盘上(它使用各种锁和分页技术)。内存中的文件是不够的。
我会创建一个临时目录来保存数据库文件,将其写入该目录,然后然后连接到它。该目录还为SQLite提供了写入提交日志的空间。
为了处理这一切,上下文管理器可能会有所帮助:
import os.path
import shutil
import sqlite3
import sys
import tempfile
from contextlib import contextmanager
@contextmanager
def sqlite_database(inmemory_data):
path = tempfile.mkdtemp()
with open(os.path.join(path, 'sqlite.db'), 'wb') as dbfile:
dbfile.write(inmemory_data)
conn = None
try:
conn = sqlite3.connect(os.path.join(path, 'sqlite.db'))
yield conn
finally:
if conn is not None:
conn.close()
try:
shutil.rmtree(path)
except IOError:
sys.stderr.write('Failed to clean up temp dir {}'.format(path))
和使用,作为:
with sqlite_database(yourdata) as connection:
# query the database
这在内存中的数据写入到磁盘,打开一个连接,可以让你使用该连接,之后清理。
为什么你有一个* remote * SQLite数据库?这远远超出了嵌入的范围。 – Makoto