sqlite3数据库命令

SQL:结构化查询语言 Structrue Query Language
是所有关系型数据库管理系统的标准语言  
非过程化语言
只需要去定义期望结果,将产生结果的过程交给外部代理(数据库引擎)来定义
根据SQL语言的功能可以这样分类:
数据定义语言:DDL

创建表:
CREATE TABLE IF NOT EXISTS 表名(列名 数据类型 约束,...);
示例:
create table IF NOT EXISTS tb_student(id integer primary key,name text not null,age integer check(age > 5));
存储类型:
integer 整型(int)
real 实型
text 文本类型
null 空类型
blob 二进制类型
常用约束条件:
primary key  主键--用于在关系表中唯一的标识一条记录
unique 唯一
not null  不为空 
check 检查
default 默认
修改表:
修改表名:
alter table 表名 rename to 新的表名;
添加一列:
alter table 表名 add column 列名 类型 约束;
alter table tb_stu add  column addr text default "CHINA";
删除表:
drop table 表名;
数据操纵语言:DML
插入
insert into 表名(列名,...)values(列值,...);
                                        示例:
insert into tb_student(id,name,age)values(1001,"zhangfei",20);
删除
delete from 表名 where 条件;
修改
update 表名 set 列名=新值 where 条件;
条件:
列名 运算符 值; 
运算符:=   !=  >   <     <=   >=
注:可以用 and 和 or 连接多个条件
          示例:
update tb_student set age=29 where name="liubei";
查询
select 列名1,... from 表名 where 条件;
select id,name,age from tb_student;
          示例:
select * from 表名; //  通配符* :表示所有列
多表查询:
tb_stu(id,name,age);
                                        1001 zhangfei  20 
tb_score(id,cid,score);
1001 A001  59
tb_curse(cid,cname,cscore);
A001 math 10 
-------------------------------
id  name  socre
1001 zhangfei           59

select 列名1,... from 表1,表2,... where 条件;
                              示例:
 select id,name,score 
from tb_student,tb_score 
where name="zhangfei" and cname="A001";

-------------------- -------------------- -------------------- -------------------- -------------------- -------------------- --------------------
练习:
删除zhangfei的数学成绩

/*第一步*/
create table stu_tb(sid integer primary key,sname text not null,age integer check(age>16));


insert into stu_tb(sid,sname,age)values(001,"zhangfei",24);
insert into stu_tb(sid,sname,age)values(002,"liubei",30);
insert into stu_tb(sid,sname,age)values(003,"guanyu",28);
insert into stu_tb(sid,sname,age)values(004,"zilong",21);

select * from stu_tb;


/*第二步*/
create table course_tb(cid integer primary key,cname test not null);

insert into course_tb(cid,cname)values(101,"语文");
insert into course_tb(cid,cname)values(102,"英语");
insert into course_tb(cid,cname)values(103,"数学");
select * from stu_tb;


/*第三步*/
create table sc_tb(sid integer,cid integer,score real);

insert into sc_tb(sid,cid,score)values(001,101,91);
insert into sc_tb(sid,cid,score)values(001,103,84);
insert into sc_tb(sid,cid,score)values(002,101,58);
insert into sc_tb(sid,cid,score)values(002,102,96);
insert into sc_tb(sid,cid,score)values(003,102,71);
insert into sc_tb(sid,cid,score)values(003,103,50);

select * from  sc_tb ;

// 删除zhangfei的数学成绩
drop from sc_tb where (select stu_tb.sid from stu_tb where sname="zhangfei")=sc_tb.sid and(select course_tb.cid from course_tb where cname="数学")=sc_tb.cid ;



猜你喜欢

转载自blog.csdn.net/sinat_39061823/article/details/76796078