从远程sqlite3数据库读取数据

4
在我的服务器上,我试图读取一堆从网络客户端发送来的sqlite3数据库,并处理它们的数据。db文件在一个S3存储桶中,我有它们的URL并且可以将它们打开到内存中。
现在的问题是sqlite3.connect只接受绝对路径字符串,我无法将内存中的文件传递给它。
conn=sqlite3.connect() #how to pass file in memory or url
c=conn.cursor()
c.execute('''select * from data;''')
res=c.fetchall()
# other processing with res

2
你为什么要使用远程SQLite数据库?这超出了它作为嵌入式数据库的范围。 - Makoto
1个回答

7

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 

这个操作将内存中的数据写入磁盘,打开一个连接,让你使用该连接,然后在完成后清理它。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接