UXDB安全数据库数据完整性包括传输完整性、存储数据完整性和实体、参照、用户定义完整性。
关系之间的参照完整性规则是“连接”关系运算正确执行的前提。
用户定义基本表时,说明主键、外键,被引用表、列和引用行为。当数据录入、更新、删除时,由数据库管理系统根据说明自动维护实体完整性和参照完整性。
系统提供定义和检查用户定义完整性规则的机制,其目的是用统一的方式由系统处理,而不是由应用程序完成,从而不仅可以简化应用程序,还提高了完整性保证的可靠性。
实体完整性:
创建测试表并插入数据:
create table student(sno integer primary key,sname char(10)); insert into student values(1,'张三'); insert into student values(2,'李四'); insert into student values(3,'王五');
插入主键重复的数据:
insert into student values(2,'赵六');
插入主键为空的数据:
insert into student(sname) values('钱七');
参照完整性:
创建外键测试表并插入数据:
create table a (id int primary key,coll varchar(4)); create table b (id_ref int ,coll varchar(4)); alter table b add constraint FK_ID foreign key(id_ref) references a(id); insert into a values (1,'ac'); insert into b values (1,'ac');
插入违反外键约束的数据:
insert into b values (2,'ac');
用户定义完整性:
创建测试表:
create type enum_sex as enum('M','F'); create table student (id int unique,name varchar(20)not null,class int default '150101',sex enum_sex );
唯一性约束验证:
insert into student values(1,'赵小红',150334,'M'); insert into student values(1,'张小美',150323,'M');
验证默认值约束:
insert into student (id,name,sex) values(3,'赵文虎','F'); select *from student where id=3;
验证非空约束:
insert into student(id,name,class,sex)values(3,null,20150609,'M');
验证自定义约束,执行以下SQL语句:
insert into student values(6,'张小虎',20150621,'N');
验证触发器约束:
创建测试表和触发器:
create table test_check(id varchar(20),age int); create or replace function pro_test_check() returns trigger as $$ begin if new.age>=120 then raise notice 'check fail'; return null; else raise notice 'check success'; return new; end if; end; $$ language pluxsql;
创建触发器:
create trigger testcheck before insert on test_check for each row execute procedure pro_test_check();
插入数据测试:
insert into test_check values('1200',39); insert into test_check values('1201',120); select * from test_check ;
第一条插入插入成功。第二条插入失败,数据未插入表中。