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

sqlite3 db .dump

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


当前回答

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

获取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;

其他回答

在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 

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

您可以对表进行选择,在每个字段后插入逗号以生成csv,或者使用GUI工具返回所有数据并将其保存为csv。

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

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

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

伸缩的答案应该是最接近的一个,但它并不适用于我的情况。一个插入查询中途中断,导出就停止了。不知道是什么原因。但是,它在.dump期间工作正常。

最后我写了一个工具来分解.dump生成的SQL:

https://github.com/motherapp/sqlite_sql_parser/