Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python save in memory sqlite

Tags:

python

sqlite

Is it possible to save my in-memory SQLite database to hard disk? If it is possible, some Python code would be awesome.

like image 446
Shansal Avatar asked Apr 29 '11 11:04

Shansal


3 Answers

(Disclosure: I am the APSW author)

The only safe way to make a binary copy of a database is to use the backup API that is part of SQLite and is exposed by APSW. This does the right thing with ordering, locking and concurrency.

To make a SQL (text) copy of the a database then use the APSW shell which includes a .dump implementation that is very complete. You can use cursor.execute() to turn the SQL back into a database.

On recent platforms you are unlikely to see much of a difference between a memory database and a disk one (assuming you turned journaling off for the disk) as the operating system maintains a file system cache. Older operating systems like Windows XP did have a default configuration of only using 10MB of memory for file cache no matter how much RAM you have.

like image 176
Roger Binns Avatar answered Nov 11 '22 04:11

Roger Binns


Per the sqlite3 python documentation, you can use the iterdump() method to make a .sql file dump of your in-memory database, and then it's trivial to apply that .sql file to a new sqlite file database.

# Convert file existing_db.db to SQL dump file dump.sql
import sqlite3, os
    
con = sqlite3.connect('existing_db.db')
with open('dump.sql', 'w') as f:
    for line in con.iterdump():
        f.write('%s\n' % line)
like image 33
mattmc3 Avatar answered Nov 11 '22 05:11

mattmc3


Yes. When you create the connection to the database, replace :memory: with the path where you want to save the DB.

sqlite uses caches for file based DBs, so this shouldn't be (much) slower.

like image 6
Aaron Digulla Avatar answered Nov 11 '22 06:11

Aaron Digulla