views:

61

answers:

2

Hey Everyone. I am trying to figure out how to copy a disk based sqlite table to a memory database in python.I know the schema of the table. Is there any easy way to do this?

A: 

this code is more general but maybe it can help you:

import sqlite3

new_db = sqlite3.connect(':memory:') # create a memory database

old_db = sqlite3.connect('test.db')

query = ""

# This will dump all the tables from test.db to a query
for line in old_db.iterdump():
    query += line

# dump old database in the new one 
new_db.executescript(query)

EDIT : for getting your specify table you can just change in the for loop like this:

name_table = "test_table"  # name of the table that you want to get.

for line in old_db.iterdump():
    if name_table in line:
        query = line
        break
singularity
This looks like it works, but how efficient is it?
Clay
@Clay: like i wrote in my answer this code is more general and generic, you can use it for dumping all the database or to dump only a given table, and for how efficient it is? the code use iterator for once (less memory) and it also create all the database in a single query, which mean no up and go(less communication).
singularity
Thanks! This will help me very much. I do like the flexability of it.
Clay
A: 

Check out the SQLite Backup API. The example is in C, but this should show you how it's done efficiently.

Hollister
Unfortunately, I don't know any C. I did think I heard somewhere that apsw (Another Python Sqlite Wrapper) Had a backup function though. Is this true?
Clay