简体   繁体   English

从sqlite3远程数据库中读取

[英]Reading from sqlite3 remote databases

In my server I'm trying to read from a bunch of sqlite3 databases (sent from web clients) and process their data. 在我的服务器中,我试图从一堆sqlite3数据库(从Web客户端发送)中读取并处理它们的数据。 The db files are in an S3 bucket and I have their url and I can open them in memory. db文件位于S3存储桶中,我有自己的URL,我可以在内存中打开它们。

Now the problem is sqlite3.connect only takes an absolute path string and I can't pass to it a file in memory. 现在的问题是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 requires database files to be stored on disk (it uses various locks and paging techniques). SQLite 要求将数据库文件存储在磁盘上(它使用各种锁和分页技术)。 An in-memory file will not suffice. 内存中的文件是不够的。

I'd create a temporary directory to hold the database file, write it to that directory, then connect to it. 我创建一个临时目录来保存数据库文件,将其写入该目录, 然后连接到它。 The directory gives SQLite the space to write commit logs as well. 该目录为SQLite提供了写入提交日志的空间。

To handle all this, a context manager might be helpful: 要处理所有这些,上下文管理器可能会有所帮助:

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))

and use that as: 并将其用作:

with sqlite_database(yourdata) as connection:
    # query the database 

This writes in-memory data to disk, opens a connection, lets you use that connection, and afterwards cleans up after you. 这会将内存数据写入磁盘,打开连接,让您使用该连接,然后在您之后清理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM