开发者

How to copy a sqlite table from a disk database to a memory database in python? [duplicate]

This question already has answers here: 开发者_StackOverflow中文版 How to load existing db file to memory in Python sqlite3? (10 answers) Closed 7 years ago.

How to copy a disk based sqlite table to a memory database in python? I know the schema of the table.


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 = "".join(line for line in old_db.iterdump())

# 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


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


An alternative, for those using python and sqlalchemy:

http://www.tylerlesmann.com/2009/apr/27/copying-databases-across-platforms-sqlalchemy/

The idea behind is to replicate the metadata from the source database to the target database and then transfer column after column.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜