2014-02-23 85 views
3

在我的服务器中,我试图从一堆sqlite3数据库(从Web客户端发送)中读取并处理它们的数据。数据库文件在S3存储桶中,我有他们的网址,我可以在内存中打开它们。从sqlite3远程数据库中读取

现在的问题是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

为什么你有一个* remote * SQLite数据库?这远远超出了嵌入的范围。 – Makoto

回答

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 

这在内存中的数据写入到磁盘,打开一个连接,可以让你使用该连接,之后清理。