如何转储数据库的一些SQLite3表(而不是所有表)的数据,并且只转储数据,而不转储模式? 转储应该是SQL格式的,因为它以后可以很容易地重新输入到数据库中,并且应该从命令行完成。类似的

sqlite3 db .dump

但是没有转储模式和选择要转储的表。


当前回答

您可以为.dump特殊命令指定一个或多个表参数,例如sqlite3 db "。Dump 'table1' 'table2' '”。

其他回答

在Python或Java或任何高级语言中。dump不起作用。我们需要手工编写转换到CSV的代码。我给出一个Python的例子。其他,例子将会很感激:

from os import path   
import csv 

def convert_to_csv(directory, db_name):
    conn = sqlite3.connect(path.join(directory, db_name + '.db'))
    cursor = conn.cursor()
    cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
    tables = cursor.fetchall()
    for table in tables:
        table = table[0]
        cursor.execute('SELECT * FROM ' + table)
        column_names = [column_name[0] for column_name in cursor.description]
        with open(path.join(directory, table + '.csv'), 'w') as csv_file:
            csv_writer = csv.writer(csv_file)
            csv_writer.writerow(column_names)
            while True:
                try:
                    csv_writer.writerow(cursor.fetchone())
                except csv.Error:
                    break

如果你有“面板数据”,换句话说,许多带有id的独立条目将this添加到with look中,它还会转储汇总统计数据:

        if 'id' in column_names:
            with open(path.join(directory, table + '_aggregate.csv'), 'w') as csv_file:
                csv_writer = csv.writer(csv_file)
                column_names.remove('id')
                column_names.remove('round')
                sum_string = ','.join('sum(%s)' % item for item in column_names)
                cursor.execute('SELECT round, ' + sum_string +' FROM ' + table + ' GROUP BY round;')
                csv_writer.writerow(['round'] + column_names)
                while True:
                    try:
                        csv_writer.writerow(cursor.fetchone())
                    except csv.Error:
                        break 

这个版本在插入的换行中工作得很好:

数据库sqlite3。sqlite3 .dump | grep '^CREATE'

实际上排除了所有以CREATE开头的行,这样不太可能包含换行符

最好的方法是采用sqlite3 db转储所做的代码,不包括模式部分。

示例伪代码:

SELECT 'INSERT INTO ' || tableName || ' VALUES( ' || 
  {for each value} ' quote(' || value || ')'     (+ commas until final)
|| ')' FROM 'tableName' ORDER BY rowid DESC

有关实际代码,请参阅:src/shell.c:838(用于sqlite-3.5.9)

您甚至可以取下外壳并注释掉模式部分并使用它。

你还没说你想怎么处理被丢弃的文件。

获取CSV文件(可以导入到几乎所有文件中)

.mode csv 
-- use '.separator SOME_STRING' for something other than a comma.
.headers on 
.out file.csv 
select * from MyTable;

获取一个SQL文件(可以重新插入到不同的SQLite数据库中)

.mode insert <target_table_name>
.out file.sql 
select * from MyTable;

您可以为.dump特殊命令指定一个或多个表参数,例如sqlite3 db "。Dump 'table1' 'table2' '”。