Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load existing db file to memory in Python sqlite3?

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?

like image 493
Adam Matan Avatar asked Oct 03 '10 13:10

Adam Matan


People also ask

Does SQLite load database into memory?

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:".

How do I load 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 read a .DB file in Python?

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.


2 Answers

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 
like image 94
Cenk Alti Avatar answered Sep 28 '22 23:09

Cenk Alti


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) 
like image 41
thinwybk Avatar answered Sep 28 '22 21:09

thinwybk