SQLite 语句基础
1. 数据定义语句(DDL:Data Definition Language)
/*!
包括create和drop等操作
在数据库中创建新表或删除表(create table或 drop table)
SQLite将数据划分为以下几种存储类型:
integer : 整型值
real : 浮点值
text : 文本字符串
blob : 二进制数据(比如文件)
*/
// 1.1 创表(create table)
create table t_person (id integer, name text, age integer) ;
create table if not exists t_person (id integer, name text, age integer); // 如果表不存在,才创建
// 1.2 删表(drop table)
drop table t_person;
drop table if exists t_person; // 如果表存在,才删除
2. 数据操作语句(DML:Data Manipulation Language)
包括insert、update、delete等操作
上面的3种操作分别用于添加、修改、删除表中的数据
// 2.1 插入数据(insert)
insert into t_person (id,name,age) values (1,'apple',35); // 数据库中的字符串内容应该用单引号 ' 括住
// 2.2 更新数据(update)
update t_person set id = 5,name = 'iPhone', age = 10; // 更改了表中所有属性值
// 2.3 删除数据(delete)
delete from t_person;
3. SQL 条件语句 where
如果只想更新或者删除某些固定的记录,那就必须在DML语句后加上一些条件
条件语句的常见格式
where 字段 = 某个值 ; // 不能用两个 =
where 字段 is 某个值 ; // is 相当于 =
where 字段 != 某个值 ;
where 字段 is not 某个值 ; // is not 相当于 !=
where 字段 > 某个值 ;
where 字段1 = 某个值 and 字段2 > 某个值 ; // and相当于C语言中的 &&
where 字段1 = 某个值 or 字段2 = 某个值 ; // or 相当于C语言中的 ||
// 3.1 where 的例子
update t_person set id=5,name=kaka,age=30 where id =1 and name !='jack’;
4. 数据查询语句(DQL:Data Query Language)
可以用于查询获得表中的数据
关键字select是DQL(也是所有SQL)用得最多的操作
其他DQL常用的关键字有where,order by,group by和having
select * from t_person // 查询所有的字段
select id,name,age from t_person where age = 23;
5. 起别名
/*
格式(字段和表都可以起别名)
select 字段1 别名 , 字段2 别名 , … from 表名 别名 ;
select 字段1 别名, 字段2 as 别名, … from 表名 as 别名 ;
select 别名.字段1, 别名.字段2, … from 表名 别名 ;
*/
示例
select name myname, age myage from t_person;
给name起个叫做myname的别名,给age起个叫做myage的别名
select p.name, p.age from t_person p;
给t_person 表起个别名叫做p,利用p来引用表中的字段
6. 计算记录的数量
/*!
select count (字段) from 表名 ;
select count ( * ) from 表名 ;
*/
示例
select count (*) from t_person;
select count ( * ) from t_person where age>= 30;
7. 排序
/*!
查询出来的结果可以用order by进行排序
select * from t_student order by 字段 ;
默认是按照升序排序(由小到大),也可以变为降序(由大到小)
select * from t_student order by age desc ; //降序
select * from t_student order by age asc ; // 升序(默认)
*/
select * from t_person order by age;
select * from t_person order by age desc; // 降序排列
// 也可以用多个字段进行排序,
// 按age倒序,id升序
select * from t_person order by age desc , id asc;
8. limit
/*!
使用limit可以精确地控制查询结果的数量,比如每次只查询10条数据
*/
select * from t_person limit 2,2 // 跳过前面两天记录取后两条记录
9. 简单的约束
Primary Key (主键,简称PK)用来唯一地标识某一条记录,主键字段默认就包含了not null 和 unique 两个约束
autoincrement 主键自动增长(必须是integer类型)
not null :规定字段的值不能为null
unique :规定字段的值必须唯一
default :指定字段的默认值
// 创建表格 id 为主键自动增长,名字不能为空,性别不能为空 默认性别为’M'
create table t_student (id integer primary key autoincrement,name text not null unique,sex text not null default 'M’)
10. 外键约束
利用外键约束可以用来建立表与表之间的联系
外键的一般情况是:一张表的某个字段,引用着另一张表的主键字段
// 创建一个表,t_student 表的 class_id 引用 t_class 表的 id
create table t_student (id integer primary key autoincrement, name text, age integer, class_id integer, constraint fk_student_class foreign key (class_id) references t_class (id));