Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a sqlite3 database from an io.BytesIO stream?

In Python3.4, is it possible to open an SQLite3 database from an io.BytesIO stream?

Something akin to:

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

The short story is: I have a stream (byte_stream) that is the sqlite database file. I can't do the following for security reasons (can't create an unencrypted file):

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

Is there some lower-level API for sqlite3 that I haven't been able to find? I assume that sqlite3.connect simply calls open() at some point and opens the file as a byte stream anyway. I'm simply trying to skip that open() step.

like image 504
dthor Avatar asked Sep 17 '15 00:09

dthor


People also ask

How do I open a SQLite database file?

Open a command prompt (cmd.exe) and 'cd' to the folder location of the SQL_SAFI. sqlite database file. run the command 'sqlite3' This should open the SQLite shell and present a screen similar to that below.

How do I connect to a SQLite database?

Select SQLite from the list. Give a Connection name for your own internal reference. For Database , click Choose a File and then select the database file on your local machine to which you want to connect. Hit Connect and you're all set!

How do I access sqlite3?

Navigate to “C:\sqlite” folder, then double-click sqlite3.exe to open it.


2 Answers

This is not possible with Python's sqlite3 module.

If you were using APSW, you could try writing your own virtual file system.

like image 181
CL. Avatar answered Sep 28 '22 22:09

CL.


It's not quite open-ing it so you can run SQL queries, but you can use https://github.com/uktrade/stream-sqlite to get at all the rows in the file.

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)

(Disclaimer: I was heavily involved in the development of stream-sqlite)

like image 31
Michal Charemza Avatar answered Sep 28 '22 23:09

Michal Charemza