加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

从sqlite3远程数据库读取

发布时间:2020-12-12 18:52:29 所属栏目:百科 来源:网络整理
导读:在我的服务器中,我试图从一堆sqlite3数据库(从Web客户端发送)中读取并处理它们的数据. db文件位于S3存储桶中,我有自己的URL,我可以在内存中打开它们. 现在的问题是sqlite3.connect只接受一个绝对路径字符串,我无法将内存中的文件传递给它. conn=sqlite3.conn
在我的服务器中,我试图从一堆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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读