当前位置:首页 > 数据库 > SQlite

我如何在python中转储单个sqlite3表?

我想只转储一个表,但从它的外观来看,没有参数.

我找到了转储的这个例子,但是适用于所有表:

# 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('%sn' % line)

解决方法:

您只能复制内存数据库中的单个表:

import sqlite3

def getTableDump(db_file, table_to_dump):
    conn = sqlite3.connect(':memory:')    
    cu = conn.cursor()
    cu.execute("attach database '" + db_file + "' as attached_db")
    cu.execute("select sql from attached_db.sqlite_master "
               "where type='table' and name='" + table_to_dump + "'")
    sql_create_table = cu.fetchone()[0]
    cu.execute(sql_create_table);
    cu.execute("insert into " + table_to_dump +
               " select * from attached_db." + table_to_dump)
    conn.commit()
    cu.execute("detach database attached_db")
    return "n".join(conn.iterdump())

TABLE_TO_DUMP = 'table_to_dump'
DB_FILE = 'db_file'

print getTableDump(DB_FILE, TABLE_TO_DUMP)

优点:
简单性和可靠性:您不必重新编写任何库方法,并且您更确信代码与sqlite3模块的未来版本兼容.

缺点:
你需要在内存中加载整个表,这可能是也可能不是很大,取决于表的大小,以及可用的内存量.


【说明】本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!