从io.BytesIO流中打开sqlite3数据库?

时间:2015-09-17 00:45:08

标签: python python-3.x sqlite

在Python3.4中,是否可以从io.BytesIO流中打开SQLite3数据库?

类似于:

with open("temp.db", "rb") as openf:
    byte_stream = io.BytesIO(openf.read())
sqlite3.connect(byte_stream)

简短的故事是:我有一个 sqlite数据库文件的流(byte_stream)。出于安全原因,我无法执行以下操作(无法创建未加密的文件):

with open("temp.db", "wb") as openf:
    openf.write(byte_stream)
sqlite3.connect("temp.db")

是否有一些我无法找到的sqlite3的低级API?我假设sqlite3.connect只是在某个时刻调用open()并将文件作为字节流打开。我只是试图跳过open()步骤。

2 个答案:

答案 0 :(得分:3)

Python的sqlite3模块无法实现这一点。

如果您使用的是APSW,可以尝试编写自己的virtual file system

答案 1 :(得分:1)

它不是很开放-ing 它以便您可以运行 SQL 查询,但您可以使用 https://github.com/uktrade/stream-sqlite 获取文件中的所有行。

import io
from stream_sqlite import stream_sqlite
import httpx

byte_stream = io.BytesIO(httpx.get('http://www.parlgov.org/static/stable/2020/parlgov-stable.db').content)

for table_name, pragma_table_info, rows in stream_sqlite(byte_stream, max_buffer_size=1_048_576):
    for row in rows:
        print(row)

(免责声明:我大量参与了stream-sqlite的开发)