使用bash合并多个SQLite数据库?

时间:2014-01-28 09:46:20

标签: linux bash sqlite

我有多个具有相同模式的sqlite数据库,我想将它们合并在一起,因为我有一个唯一的列,可能存在重复的风险,我使用insert or ignore,在sqlite中它会是容易:

sqlite3 database.db3
sqlite> attach './db1.db3' as s1;
sqlite> attach './db2.db3' as s2;
sqlite> attach './db3.db3' as s3;
sqlite> insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s1.table;
sqlite> insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s2.table;
sqlite> insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s3.table;
sqlite> .exit

我读了关于转储但我不想合并整个架构,只是一个表,所以我想到了这个解决方案,现在直到这里一切都很好,但我需要通过bash运行所有这些,我尝试了以下但它没有:

sqlite3 database.db3 "attach './db1.db3' as s1;"
sqlite3 database.db3 "attach './db2.db3' as s2;"
sqlite3 database.db3 "attach './db3.db3' as s3;"
sqlite3 database.db3 "select count(*) from s1.table;"
sqlite3 database.db3 "select count(*) from s2.table;"
sqlite3 database.db3 "select count(*) from s3.table;"

它说Error: no such table: s1.table

我做错了什么

2 个答案:

答案 0 :(得分:5)

使用heredoc,如下所示:

sqlite3 database.db3 << "EOF"
attach './db1.db3' as s1;
attach './db2.db3' as s2;
attach './db3.db3' as s3;
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s1.table;
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s2.table;
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s3.table;
.exit
EOF

或者,将所有命令放入文件并按以下方式运行:

sqlite3 database.db3 < commandsFile

答案 1 :(得分:3)

1)创建一个文本文件,其中包含您要输入sqlite命令行程序的行,如下所示:

attach './db1.db3' as s1;
attach './db2.db3' as s2;
attach './db3.db3' as s3;
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s1.table;
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s2.table;
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s3.table;
.exit

然后只需致电sqlite3 database.db < commands.txt

2)使用shell

#!/bin/bash 

sqlite3 database.db <<"EOF"
attach './db1.db3' as s1;
attach './db2.db3' as s2;
attach './db3.db3' as s3;
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s1.table;
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s2.table;
insert or ignore into table (c1, c2, c3) select c1, c2, c3 from s3.table;
.exit
EOF