2016 - 3 - 12 SQLite的学习之SQL语言入门

时间:2023-03-09 06:15:15
2016 - 3 - 12 SQLite的学习之SQL语言入门

1.SQL语句的特点:

1.1 不区分大小写

1.2 每条语句以;结尾

2.SQL语句中常用关键字:

select,insert,update,from,create,where,desc,order,by,group,table,alter,view,index等。

数据库中不能出现与上述关键字重名的表名和字段。

3.SQL语言种类:

3.1

数据定义语句: Data Defination Language; (DDL)

包括create和drop等操作

包括创建表或者删除表(create table 和 drop table)

3.2

数据操作语言: Data Manipulation Language (DML)

包括insert,update,delete等操作

上述三种操作分别作用于添加,修改,删除表中数据

3.3

数据查询语言:Data Query Language (DQL)

关键字select是DQL中用的最多的操作

其他常用的DQL中的关键字如 where,order by, group by 和 having.

4.SQL语句使用举例

4.1 DDL (数据定义语言)

4.1.1 创建表格

creat table 表名(字段名1 字段类型1,字段名2 字段类型2)

例如 : CREATE table t_student(id integer PRIMARY key, name text);

实际上SQLite是无类型的,就是是申明为integer类型,一样可以存储字符串数据(主键除外)

4.1.2 删除表格

drop table 表名

例如:DROP TABLE t_student;

4.2DML(数据操作语言)

4.2.1 插入数据

insert to 表名 (字段1,字段2)values(字段1的值,字段2的值)

例如:INSERT into t_student(id,name)VALUES(1,'zhengli');

4.2.2 修改数据

update 表名 set 字段1 = 字段1 新值

例如: update t_student set name = 'zhengli';(注意这样写会将表中的所有name的值更改)

4.2.3 删除数据

delete from 表名

例如: delete from t_student ; (与上面的语句一样,会删除表中所有数据!但不会删除表);

在上面的所有语句中,都可以加上条件语句,例如: update t_student set name = 'tangyi'where id = 1;

这样就只会修改 id =1 的数据。同时可以用and表示C语言中的&& or表示||。

4.3 DQL语句 (数据查询语句)

4.3.1 按照条件查询

select 字段1,字段2,... from 表名

select *from 表名  (查询表中所有字段)

4.3.2  排序查询

select * from 表名 oder by 字段名(默认升序)

select * from 表名 order by 字段名 desc (降序)

4.3.3  limit

select *from 表名 order by 字段名 (升序) limit 数值1,数值2

表示从表中取数据并按升序排列,跳过前数值1个数据,取数值2个数据

如: select * from t_student order by id limit 0,5;

升序排序取出前五条数据。

select *from t_student order by age desc limit 2,3;

降序排序 跳过前2条数据 取之后的3条数据

4.3.4 约束

内键约束

建表时可以给特定的字段设置一些约束条件,常见的约束有

1.not null 该字段不能为空

2.unique 该字段的值唯一,不能重复

3. default 制定该字段的默认值

例如:  create table t_student (id integer primary key , name text not null unique,age integer not null default 1)

表名该表中的 name字段不能为空且不能重复,age不能为空且默认为1;

外键约束

利用外键约束,可以建立表与表之间的联系

外键约束的一般情况是,一张表的某个字段,引用着另一张表的主键字段

例如:

create table t_student(id integer primary key ,name text,class_id integer constraint fk_t_student_class_id_t_class_id foreign key (class_id) references t_class(id));