The sqlite3
command line tool allows me to .save <file>
the in-memory database without having to dump the SQL in its string/script form.
I'd like to do something similar without writing too much boilerplate code. However, I do not always want to save it, which is why I would like to avoid an on-disk DB before I actually need it.
Is there a way to do this in Python, short of dumping the SQL in string form and importing it to the on-disk file (which I know how to do and have already implemented)?
There doesn't seem to be a single line solution.
Backing up an in-memory
sqlite database can be done using the iterdump method of the connection object. Of course, this is only just short of dumping the sql text and importing it.
import sqlite3
# set up a database in memory
c = sqlite3.connect(':memory:')
c.execute('CREATE TABLE my_table (id int, name text);')
c.execute("INSERT INTO my_table VALUES (1, 'bruce'), (2, 'wayne'), (3, 'BATMAN');")
c.commit()
# write database to disk
c2 = sqlite3.connect('mydb.db')
with c2:
for line in c.iterdump():
if line not in ('BEGIN;', 'COMMIT;'): # let python handle the transactions
c2.execute(line)
c2.commit()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With