一:概述
(1)介绍
(2)特性
二:基本操作
-- 用户表
create table user(uid int primary key,username varchar(50) not null,password varchar(50) not null
);-- 用户信息操作日志表
create table user_logs(id int primary key auto_increment,time timestamp,log_text varchar(255)
);-- 需求1:当user表添加一行数据,则会自动在user_log添加日志记录
-- 定义触发器 trigger_test1
create trigger trigger_test1 after insert
on user for each row
insert into user_logs values(NULL,now(),'有新用户添加');-- 在user表添加数据,让触发器自动执行
insert into user values(1,'张三','123456');-- 需求2:当user表数据被修改时,则会自动在user_log添加日志记录
delimiter $$
create trigger trigger_test3 before update
on user for each row
begininsert into user_logs values(NULL,now(),'有用户信息被修改');
end $$
delimiter ;-- 在user表修改数据,让触发器自动执行
update user set password = '888888' where uid = 1;
三:NEW和OLD
-- 删除触发器
drop trigger if exists trigger_test2;-- NEW
-- 定义触发器:trigger_test3
drop trigger if exists trigger_test3;
create trigger trigger_test3 after insert
on user for each row
insert into user_logs values (NULL,now(),concat('有新用户添加,信息为:',NEW.uid,NEW.username,NEW.password));insert into user values(5,'赵六','123456');-- update类型的触发器
-- OLD
drop trigger if exists trigger_test4;
create trigger trigger_test4 after update
on user for each row
insert into user_logs values (NULL,now(),concat('有用户信息修改,修改前信息为:',OLD.uid,OLD.username,OLD.password));update user set password = '999999'where uid = 4;-- NEW
drop trigger if exists trigger_test5;
create trigger trigger_test5 after update
on user for each row
insert into user_logs values (NULL,now(),concat_ws(',','有用户信息修改,修改后信息为:',NEW.uid,NEW.username,NEW.password));update user set password = '000000'where uid = 1;-- delete类型的触发器
-- OLD
drop trigger if exists trigger_test6;
create trigger trigger_test6 after delete
on user for each row
insert into user_logs values (NULL,now(),concat_ws(',','有用户被删除,被删除用户信息为:',OLD.uid,OLD.username,OLD.password));delete from user where uid = 5;
四:其他操作
五:注意事项