、数据库定义语言 DDL
在关系型数据库中,数据库中的表 Table、视图 View、索引 Index、关系 Relationship 和触发器 Trigger 等等,构成了数据库的架构 Schema。 在 SQL 语句中,专门有一些语句用来定义数据库架构,这些语句被称为“数据库定义语言”,即 DDL。
SQLite 数据库引擎支持下列三种 DDL 语句:
CREATE
ALTER TABLE
DROP
其中,CREATE 语句用来建立表 Table、视图 View、索引 Index、关系 Relationship 和触发器 Trigger, DROP语句用来删除表 Table、视图 View、索引 Index、关系 Relationship 和触发器 Trigger, ALTER TABLE 语句用来改变表的结构。
今天这一篇只涉及到表的相关内容,视图、触发器等到后面再讲。
2、SQLite 中的数据类型
SQLite 数据库中的数据通常由如下几种经常使用的数据类型组成:
NULL - 空值
INTEGER - 有符号整数
REAL - 浮点数
TEXT - 文本字符串
BLOB - 二进制数据,如图片、声音等等
SQLite 也能够接受其余数据类型。
3、建立表 CREATE TABLE
首先,建立一个 test.db 数据库并进入 SQLite 命令行环境,还记得怎么作吗?
[xiazhujie@localhost]:~$ sqlite3 test.db
-- Loading resources from /home/xiazhujie
/.sqliterc
SQLite version 3.7.4
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
sqlite>
向上面这样,咱们就在终端中建立了一个 test.db 数据库,而且经过 .tables 命令查询数据库中的表,结果没有任何返回,由于数据库原本就是空的嘛。
下面咱们建立一个 Student 表,其中包含 Id、Name、Age 等字段.
sqlite> CREATE TABLE Students(Id integer,Name text,age integer);
sqlite> .tables
Students
sqlite> .schema Students
CREATE TABLE Students(Id integer,Name text,age integer);
向上面这样,一个 Students 表就被创建了,这回再运行 .tables 命令就有响应了,系统告诉咱们数据库中如今有一个 Students 表, 运行 .schema 命令,返回了咱们建立这个表的 SQL 命令。
4、修改表 ALTER TABLE
SQLite 仅仅支持 ALTER TABLE 语句的一部分功能,咱们能够用 ALTER TABLE 语句来更改一个表的名字,也可向表中增长一个字段(列),可是咱们不能删除一个已经存在的字段,或者更改一个已经存在的字段的名称、数据类型、限定符等等。
改变表名 - ALTER TABLE 旧表名 RENAME TO 新表名
增长一列 - ALTER TABLE 表名 ADD COLUMN 列名 数据类型 限定符
下面咱们来演示一下,将前面的 Students 表的名字改成 Teachers
sqlite>
sqlite> .tables
Students
sqlite> ALTER TABLE Students RENAME TO Teachers;
sqlite> .tables
Teachers
sqlite>
原来数据库中只有一个 Students 表,更名之后再运行 .tables 命令,发现 Students 表已经没了,如今变成了 Teachers 表。
下面改变 Teachers 表的结构,增长一个 Sex 列
sqlite> .schema Teachers
CREATE TABLE "Teachers"(Id integer,Name text,age integer);
sqlite> ALTER TABLE Teachers ADD COLUMN Sex text;
sqlite> .schema Teachers
CREATE TABLE "Teachers"(Id integer,Name text,age integer, Sex text);
5、删除表 DROP TABLE
删除一个表很简单,只要给出表名便可
删除表 - DROP TABLE 表名
下面,咱们将 test.db 中的 Teachers 表删除
sqlite> .tables
Teachers
sqlite> DROP TABLE Teachers;
sqlite> .tables
删除 Teachers 表后再运行 .tables 命令,发现数据库已经空了。
原文:http://www.cnblogs.com/myqiao/category/309151.htmlhtml