I have an existing sqlite3
db file, on which I need to make some extensive calculations. Doing the calculations from the file is painfully slow, and as the file is not large (~10 MB
), so there should be no problem to load it into memory.
Is there a Pythonic way to load the existing file into memory in order to speed up the calculations?
An SQLite database is normally stored in a single ordinary disk file. However, in certain circumstances, the database might be stored in memory. The most common way to force an SQLite database to exist purely in memory is to open the database using the special filename ":memory:".
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.
First, establish a connection to the SQLite database by creating a Connection object. Next, create a Cursor object using the cursor method of the Connection object. Then, execute a SELECT statement. After that, call the fetchall() method of the cursor object to fetch the data.
Here is the snippet that I wrote for my flask application:
import sqlite3 from io import StringIO def init_sqlite_db(app): # Read database to tempfile con = sqlite3.connect(app.config['SQLITE_DATABASE']) tempfile = StringIO() for line in con.iterdump(): tempfile.write('%s\n' % line) con.close() tempfile.seek(0) # Create a database in memory and import from tempfile app.sqlite = sqlite3.connect(":memory:") app.sqlite.cursor().executescript(tempfile.read()) app.sqlite.commit() app.sqlite.row_factory = sqlite3.Row
What about sqlite3.Connection.backup(...)
? "This method makes a backup of a SQLite database even while it’s being accessed by other clients, or concurrently by the same connection." Availability: SQLite 3.6.11 or higher. New in version 3.7.
import sqlite3 source = sqlite3.connect('existing_db.db') dest = sqlite3.connect(':memory:') source.backup(dest)
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