sqlite基本操作

对数据库操作的一个梳理。

数据库

.database 查看当前的数据库文件

创建数据库

sqlite3 testDB.db

.table 查看当前数据库文件的表

.schema [表名] 查看数据库中某一个表的定义

创建表

create table 表名;

示例:

1
2
3
4
5
6
create table student(
id int not null primary key),
name varchar(20) not null,
age int not null,
address varchar(20) not null
);

删除表

drop table [表名];

示例:

1
drop table student;

清空表

truncate table [表名];

truncate table student;

对表中数据的增删查改

insert into [表名] ([字段名1],[字段名2]…)
values ([常量1],[常量2]…);
insert into [表名] ([字段名1],[字段名2]…)
select [查询语句
];

示例:

1
2
3
4
insert into student (id,name,age,address)
values (1,"hzq",22,"china");
insert into student (id,name,age,address)
select (id,name,age,address) from student_T;

delete from [table] [where表达式]

示例:

1
2
//删除ID为1的学生信息
delete from student where id=1;

select [ALL|DISTINCT] [目标列1…]
from [表名]
[where表达式]
[order by 表达式]
[limit 表达式];

示例:

1
2
3
4
5
//显示来自中国的id最大的前4位
select name from student
where address="china"
order by id DESC
limit 4;

update [表名] set [列名]=[需要修改成为的值,或者表达式] [where表达式];

示例:

1
update student set age=18 where id=1;

约束条件:

where

指定条件。
同时可以通过关系运算符和逻辑运算符”>,<,=,like,not”

示例:

1
2
3
4
//查询student表中,id=1的结果;
select * from student where id=1;
//查询student表中,id大于10小于100的结果。
select * from student where id>10 and id < 100;

order by

按照一定的顺序显示结果。支持升序和降序。
order by [列名] ASC; //升序
order by [列名] DESC; //降序

示例:

1
2
//查询所有的学生,并按照降序排序
select * from student order by id DESC;

limit

限制输出结果的数量。

limit [int] [offset [int]];

示例:

1
2
3
//查询student表,从第2(1+1)个数据开始,只显示3个。
select * from student limit 3 offset 1;
注意:数据库中的表的下标,是从0开始。

like:

通过通配符来匹配达标的项。

可以使用的通配符有两个:

  • 百分号:%
  • 下划线:_

%表示零个或者多个字符,_表示一个数字或字符。

示例

1
2
3
4
5
where salary like "200%" 找到200开头的结果
where salary like "%200%" 找到含有200的结果
where salary like "_00%" 找到第二位和第三位都是0的结果
where salary like "2_%_%" 找到以2开头,并且长度至少有3位的结果
where salary like "2%3" 找到2开头,3结尾的结果

distinct

与select一起使用,用来查找出不重复的结果。

示例:

1
2
//看学生都是来自哪几个地方
select distinct address from student

group by

与select连用,将相同的数据进行分组。

注意:group by要放在where之后,order by之前。

示例:

1
2
//显示出每个学生的名字,以及他的总分
select name,SUM(grade) from student group by name;

having

指定过滤条件, 与group by连用。

示例:

1
2
//输出age次数出现了两次以上的结果
select name,age from student group by age having COUNT(age)>=2;

如果文章对您有用请随意打赏,谢谢支持!