【问题标题】:Reading from sqlite3 remote databases从 sqlite3 远程数据库读取
【发布时间】:2014-02-23 12:20:10
【问题描述】:

在我的服务器中,我试图从一堆 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

【问题讨论】:

  • 为什么你有一个remote SQLite 数据库?这使它完全脱离了嵌入的范围。

标签: python sqlite


【解决方案1】:

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 

这会将内存中的数据写入磁盘,打开一个连接,让您使用该连接,然后在您之后进行清理。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-05
    • 1970-01-01
    相关资源
    最近更新 更多