转于 SQLite 入门教程(二)建立、修改、删除表html
在关系型数据库中,数据库中的表 Table、视图 View、索引 Index、关系 Relationship 和触发器 Trigger 等等,构成了数据库的架构 Schema。 在 SQL 语句中,专门有一些语句用来定义数据库架构,这些语句被称为“数据库定义语言”,即 DDL。java
SQLite 数据库引擎支持下列三种 DDL 语句:sql
其中,CREATE 语句用来建立表 Table、视图 View、索引 Index、关系 Relationship 和触发器 Trigger, DROP语句用来删除表 Table、视图 View、索引 Index、关系 Relationship 和触发器 Trigger, ALTER TABLE 语句用来改变表的结构。数据库
今天这一篇只涉及到表的相关内容,视图、触发器等到后面再讲。ubuntu
SQLite 数据库中的数据通常由如下几种经常使用的数据类型组成:架构
SQLite 也能够接受其余数据类型。post
首先,建立一个 test.db 数据库并进入 SQLite 命令行环境,还记得怎么作吗?spa
myqiao@ubuntu:~$ sqlite3 test.db -- Loading resources from /home/myqiao/.sqliterc SQLite version 3.7.4 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite> .tables sqlite>
向上面这样,咱们就在终端中建立了一个 test.db 数据库,而且经过 .tables 命令查询数据库中的表,结果没有任何返回,由于数据库原本就是空的嘛。.net
下面咱们建立一个 Student 表,其中包含 Id、Name、Age 等字段.命令行
sqlite> 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); sqlite>
向上面这样,一个 Students 表就被创建了,这回再运行 .tables 命令就有响应了,系统告诉咱们数据库中如今有一个 Students 表, 运行 .schema 命令,返回了咱们建立这个表的 SQL 命令。
SQLite 仅仅支持 ALTER TABLE 语句的一部分功能,咱们能够用 ALTER TABLE 语句来更改一个表的名字,也可向表中增长一个字段(列),可是咱们不能删除一个已经存在的字段,或者更改一个已经存在的字段的名称、数据类型、限定符等等。
下面咱们来演示一下,将前面的 Students 表的名字改成 Teachers
sqlite> sqlite> .tables Students sqlite> ALTER TABLE Students RENAME TO Teachers; sqlite> .tables Teachers sqlite>
原来数据库中只有一个 Students 表,更名之后再运行 .tables 命令,发现 Students 表已经没了,如今变成了 Teachers 表。
下面改变 Teachers 表的结构,增长一个 Sex 列
sqlite> 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); sqlite>
删除一个表很简单,只要给出表名便可
下面,咱们将 test.db 中的 Teachers 表删除
sqlite> sqlite> .tables Teachers sqlite> DROP TABLE Teachers; sqlite> .tables sqlite>
删除 Teachers 表后再运行 .tables 命令,发现数据库已经空了。
其实建立一个表远没有这么简单,表的每一列能够有不少限定符,好比主列、非空、限制、默认值、惟1、键等等,这些内容留到下一篇吧