从sqlite3远程数据库读取

在我的服务器中,我试图从一堆sqlite3数据库(从Web客户端发送)中读取并处理它们的数据. 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

解决方法:

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 

这会将内存数据写入磁盘,打开连接,让您使用该连接,然后在您之后清理.

相关文章

SQLite架构简单,又有Json计算能力,有时会承担Json文件/RES...
使用Python操作内置数据库SQLite以及MySQL数据库。
破解微信数据库密码,用python导出微信聊天记录
(Unity)SQLite 是一个软件库,实现了自给自足的、无服务器...
安卓开发,利用SQLite实现登陆注册功能