官方的例子如下
Using sqlite3 in a shell script
One way to use sqlite3 in a shell script is to use “echo” or “cat” to generate a sequence of commands in a file, then invoke sqlite3 while redirecting input from the generated command file. This works fine and is appropriate in many circumstances. But as an added convenience, sqlite3 allows a single SQL command to be entered on the command line as a second argument after the database name. When the sqlite3 program is launched with two arguments, the second argument is passed to the SQLite library for processing, the query results are printed on standard output in list mode, and the program exits. This mechanism is designed to make sqlite3 easy to use in conjunction with programs like “awk”. For example:
$ sqlite3 ex1 ’select * from tbl1′ |
> awk ’{printf ”<tr><td>%s<td>%s\n”,$1,$2 }’
<tr><td>hello<td>10
<tr><td>goodbye<td>20
$
我自己的例子
sqlite3 ex1.db ‘insert into table1 values(1,”ere”,”erer”,1,”dfdfd”)’;
注意要把sql语句用单引号括起来,所以原来sql里面单引号相应变换成双引号,搞定。
如果想调用shell 变量,则需要将变量先单引号再双引号
sqlite3 ex1.db ‘insert into table1 values(”‘$a’”,”‘$a’”,1,”‘$a’”);’
但是一旦shell变量里面有单引号,比如I’m jack,那么上述写法就会出错。因为在shell里面不能简单的通过\’ 来转义
所以只能更改变量 echo $var | sed “s/’/”/g” 将一个单引号改成两个,I”m jack 这样才能正常工作
其他sqlite的特别用法
sqlite可以在shell底下直接执行命令:
sqlite3 film.db "select * from film;"输出 HTML 表格:
sqlite3 -html film.db "select * from film;"将数据库「倒出来」:
sqlite3 film.db ".dump" > output.sql利用输出的资料,建立一个一模一样的数据库(加上以上指令,就是标准的SQL数据库备份了):
sqlite3 film.db < output.sql在大量插入资料时,你可能会需要先打这个指令:
begin;插入完资料后要记得打这个指令,资料才会写进数据库中:
commit;
