**保护数据库**
一、完整性
1.定义
2.分类:实体完整性、域完整性、用户定义完整性
3.创建约束(主键、外键)
(1)创建表的同时创建约束
1)主键primary key
2)外键foreign key
父关键字在自己表中必须是主键;
父子必须完全一样
3)唯一unique
4)默认值default
举例
create table student
(sno char(4) primary key,
sname char(20) not null,
sage int,
ssex char(2) default ‘男’);
create table sc
(sno char(4),
cno char(3),
grade int,
constraint pk_sc primary key(sno,cno),
constraint fk1_sc foreign key(sno) references student(sno));
(2)表已经存在,添加约束
1)主键
alter table student
add primary key(sno);
alter table sc
add primary key(sno,cno);
2)外键
alter table sc
add constraint fk1_sc foreign key(sno) references student(sno);
3)唯一
alter table student
add constraint uni unique(sname);
4.查看约束
show create table student;
5.删除约束
1)主键
alter table student
drop primary key;
2)外键
alter table sc
drop foreign key fk1_sc;
3)唯一
alter table student
drop index uni;
二、安全性
1.作用:非法用户、非授权用户
2.管理用户mysql> use mysql;
(1)创建
create user u1@localhost
identified by ‘u1’;
尝试登录,是否成功,u1能否使用xkdb?mysql?数据库
create user u2@localhost identified by ‘u2’,
u3@localhost identified by ‘u3’,
u4@localhost identified by ‘u4’;
(2)修改
修改用户名
rename user u1@localhost to U1@localhost;
修改密码
set password for U1@localhost = password(‘U1’);
(3)查看
select host,user,password
from user;
(4)删除
drop user U1@localhost
3.管理权限
(1)全局层级
grant all on . to U1@localhost;
验证权限:登录、测试拥有的权限、测试没有的权限
(2)数据库级
grant all on xkdb.* to u2@localhost;
验证权限:登录、测试拥有的权限、测试没有的权限
(3)表级
grant select on xkdb.student to u3@localhost;
(4)列级
grant select(sno,cno) on xkdb.sc to u4@localhost;