1.获得命令行程序
SQLite命令行程序(CLP)是开始使用SQLite的最好选择,按照如下步骤获取CLP:
1).打开浏览器进入SQLite主页,www.sqlite.org。
2).单击页面顶部的下载链接(Download)选项,进入下载页面。
3).滚动鼠标到“Precompiled Binaries for Windows”,选择sqlite-shell-win32-x86-3071401.zip(第一项),点击下载。
4).使用解压工具,将其解压。zip文件中包含一个sqlite3.exe文件,可以从解压文件所在位置使用sqlite;如果你想从任何目录下运行CLP,需要将该文件复制到Windows系统路径下。默认情况下,Windows中工作的路径是根分区下的(C:\Windwos\System32)。
5).打开运行窗口,输入CMD,调出Windows命令行窗口。
6).在命令行窗口输入sqlite3并按回车,将出现SQLite命令行提示符。当SQLite命令行提示符出现时,输入.help,将出现一列类似相关命令的说明。输入.exit后退出程序。
现在你已经有一份可以工作的安装在系统上的SQLite CLP副本了。
如果此刻就要使用SQLite,请关注下一节(Shell 模式的CLP)。
创建首个 SQLite 数据库
现在你已经安装了 SQLite 数据库,接下来我们创建首个数据库。在命令行窗口中输入如下命令来创建一个名为 test.db 的数据库。
sqlite3 test.db (如果test.db不存在则创建,存在则打开)
创建表:
sqlite>createtablemytable(idintegerprimarykey, value text);
2 columns were created.
该表包含一个名为 id 的主键字段和一个名为 value 的文本字段。
注意: 最少必须为新建的数据库创建一个表或者视图,这么才能将数据库保存到磁盘中,否则数据库不会被创建。
接下来往表里中写入一些数据:
sqlite>insertintomytable(id, value)values(1,'Micheal');
sqlite>insertintomytable(id, value)values(2,'Jenny');
sqlite>insertintomytable(value)values('Francis');
sqlite>insertintomytable(value)values('Kerk');
查询数据:
sqlite>select*frommytable;
1|Micheal
2|Jenny
3|Francis
4|Kerk
SQlite内置命令
它除了能执行SQL语句以外还提供一组内置的命令,它们是以点.开始,比如说查看帮助信息就是.help退出是.exit跟.quit
设置格式化查询结果:
sqlite> .modecolumn (注意没有分号,否则报错)
sqlite> .headeron; (注意有分号,关于这点比较奇怪,一时有分号,一时没有。)
sqlite>select*fromtest;
id value
----------- -------------
1 Micheal
2 Jenny
3 Francis
4 Kerk
.mode column 将设置为列显示模式,.header 将显示列名。
修改表结构,增加列:
sqlite>altertablemytableaddcolumnemail textnotnull''collatenocase;;
创建视图:
sqlite>createviewnameviewasselect*frommytable;
创建索引:
sqlite>createindextest_idxonmytable(value);
4. 一些有用的 SQLite 命令
显示表结构:
sqlite> .schema[table]
显示如:
sqlite> .schema mytable
CREATE TABLE mytable(id integer primary key,value text, email text);
CREATE INDEX test_idx on mytable(value);
获取所有表和视图:
sqlite > .tables (注意没有分号)
获取指定表的索引列表:
sqlite > .indices [table]
导出数据库到 SQL 文件:
sqlite > .output[filename ]
sqlite > .dump
sqlite > .outputstdout
文件内容为:
PRAGMA foreign_keys=OFF;BEGIN TRANSACTION;CREATE TABLE member(id integer primary key,age integer);CREATE TABLE mytable(id integer primary key,value text, email text);INSERT INTO "mytable" VALUES(1,'suming',NULL);INSERT INTO "mytable" VALUES(2,'suming2',NULL);INSERT INTO "mytable" VALUES(3,'suming3',NULL);CREATE VIEW nameview as select * frommytable;CREATE INDEX test_idx onmytable(value);COMMIT;
从 SQL 文件导入数据库:
sqlite > .read[filename ]
格式化输出数据到 CSV 格式:
sqlite >.output[filename.csv ]
sqlite >.separator ,
sqlite >select*fromtest;
sqlite >.outputstdout
从 CSV 文件导入数据到表中:
sqlite >createtablenewtable ( idintegerprimarykey, value text );
sqlite >.import [filename.csv ] newtable
备份数据库:
/* usage: sqlite3 [database] .dump > [filename] */
sqlite3 mytable.db .dump > backup.sql
恢复数据库:
/* usage: sqlite3 [database]
sqlite3 mytable.db
更多: