* 非交互式 * bash 脚本中的 SQLite3 用法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42245816/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
*Non-interactive* SQLite3 usage from bash script
提问by Alexander Mills
I see plenty of examples showing how to use the sqlite3 interactive shell, e.g.:
我看到很多示例展示了如何使用 sqlite3 交互式 shell,例如:
$ sqlite3
$ sqlite3> SELECT * from x;
but I am looking for a way to create a table in a SQLite3 database with a bash script, aka, non-interactively - anyone know how to do that?
但我正在寻找一种使用 bash 脚本(即非交互方式)在 SQLite3 数据库中创建表的方法——有人知道怎么做吗?
For example, the following doesn'tseem to work, it remains interactive:
例如,下面的不确实似乎工作,但它仍然互动:
#!/bin/bash
sqlite3 test.db "create table n (id INTEGER PRIMARY KEY,f TEXT,l TEXT);"
sqlite3 test.db "insert into n (f,l) values ('john','smith');"
sqlite3 test.db "select * from n";
Also one aside question - does it ever help to "wake up SQLite3" by calling "sqlite3" as background process - or is it pretty much always running in the background on MacOS and Linux?
还有一个问题——通过调用“sqlite3”作为后台进程来“唤醒SQLite3”是否有助于“唤醒SQLite3”——或者它是否几乎总是在MacOS和Linux的后台运行?
采纳答案by Alexander Mills
Looks like it's as simple as
看起来就这么简单
#!/bin/bash
sqlite3 test.db "create table n (id INTEGER PRIMARY KEY,f TEXT,l TEXT);"
sqlite3 test.db "insert into n (f,l) values ('john','smith');"
sqlite3 test.db "select * from n";
from https://mailliststock.wordpress.com/2007/03/01/sqlite-examples-with-bash-perl-and-python/
来自https://mailliststock.wordpress.com/2007/03/01/sqlite-examples-with-bash-perl-and-python/
回答by varro
While the above should work, I think it is better not to have to invoke sqlite3 multiple times, therefore I think the following is preferable:
虽然上述应该有效,但我认为最好不要多次调用 sqlite3,因此我认为以下内容更可取:
#!/bin/sh
sqlite3 test.db <<EOF
create table n (id INTEGER PRIMARY KEY,f TEXT,l TEXT);
insert into n (f,l) values ('john','smith');
select * from n;
EOF
Note that unless you reallyneed to use bash, you should prefer "/bin/sh" as your shebang, for portability reasons.
请注意,除非您确实需要使用 bash,否则出于可移植性的原因,您应该更喜欢“/bin/sh”作为您的shebang。
回答by marabu
You can disable interactive mode using the -batch option:
您可以使用 -batch 选项禁用交互模式:
sqlite3 -batch test.db "create table n (id INTEGER PRIMARY KEY,f TEXT,l TEXT);"