[toc]
sqlite3 program
Mac OS 上已经预装了 sqlite3
1 | $ which sqlite3 |
进入 sqlite3 命令行环境,并创建表格
1 | $sqlite3 ex1 |
dot-command
点命令是 sqlite3 的设置输出命令,有一些规则需要遵循:
- 必须以 “.” 开头;
- 单行执行,不支持多行
- 不能在 SQL 中
- 不能够写注释
通过 .help 可以查看所有的点命令
注意:
- sqlite 中 SQL 语句不区分大小写;
- 每个 SQL 语句都需要分号结束,如果没有分号,Enter 之后,sqlite3 会继续让你输入,知道遇到分号为止
dot-command 修改输出格式
1 | sqlite> .tables |
.tables 查看当前数据库中的表, select from tabl2; 查看 tabl2 表中的数据,并且以 list* 方式展示出来。 sqlite3 program 能够以 8 种方式展示输出结果:
- csv
- column
- html
- insert
- line
- list
- quote
- tabs
- tcl
通过 .mode [方式名字] 可以修改当前的展示模式
1 | sqlite> select * from tabl2; |
默认是 list 模式,上面分别以 list、csv、html、tabs 模式进行展示。
除此之外,.separator 可以修改分隔符,比如我们以 “ ~ “ 作为分割
1 | sqlite> .separator " ~ " |
当然,如果通过 .mode 再次修改输出格式的话, .separator 的操作就会被重置,这一点需要注意。
line & column 模式
通过 .mode line 和 .mode column 可以将输出格式修改成行和列模式,实现如下:
- 行模式
1 | sqlite> .mode line |
- 列模式
1 | sqlite> .mode column |
通过 .header on/off 列模式可以将 header 部分展示出来
1 | sqlite> .header on |
修改列宽 .width col1W col2W … colnW
1 | sqlite> .width 1 10 |
.width 后面跟着的数字分别表示第几行的宽度,如果没有就是没有限制
插入模式输出
有时候,我们需要在另一个表中插入与当前表相同的数据,那么久可以通过 insert 模式来实现
1 | sqlite> .mode insert new_table |
将查询结果写入文件
.output and .once 将 sqlite3 的标准输出重定向到指定文件中
1 | $touch output.txt |
.once 用法与 .output 用法一致,只不过 .once 只会让 sliqte3 执行一次非标准输出
1 | sqlite> .once output.txt |
通过 ‘|’ 打开保存的文件
1 | sqlite> .once '|open -f' |
如图所示,会将结果存储到一个 txt 文件中,然后打开:
File I/O Function
以存储图片为例:
- 新建一张 images 表
- 在当前目录中添加一张图片, icon.png
- readfile(‘icon.png’)
1
2
3
4
5
6
7
8
9
10
11sqlite> create table images
...> (
...> name text,
...> type text,
...> img blob
...> );
sqlite> insert into images(name,type,img) values ('icon','png',readfile('icon.png'));
sqlite> select * from images;
name type img
---------- ---------- ----------
icon png �PNG
读取数据库中的图片,writefile(x,y) 负责将图片写入与数据库相同的目录中
1 | sqlite> select writefile('img.png',img) from images where name = 'icon'; |
上面实现了 sqlite3 对图片的存储和读取,分别用到了 readfile() 和 writefile() 函数,图片格式为 blob