概念
触发器类型 | new和old |
---|---|
insert 型触发器 | new 表示将要或者已经新增的数据 |
update 型触发器 | old表示修改之前的数据,new表示修改之后的数据 |
delete 型触发器 | old表示将要或者已经删除的数据 |
before 之前触发,after 之后触发
环境:
insert 类型触发器的语法
CREATE TRIGGER tb_user_insert_trigger
AFTER INSERT ON tb_user FOR EACH ROW
INSERT INTO user_log(id,operation,operation_time,operation_id,operation_params)VALUES
(NULL,'insert',NOW(),new.id,
CONCAT('插入的数据内容为: id=',new.id,',username=',new.username,',password=',new.password));
END;
INSERT INTO tb_user(id,username,`password`)VALUES(1,'haha','123456');
该触发器表示在向tb_user表中插入数据后触发该触发器,向日志表中插入操作日志
SHOW TRIGGERS;
DROP TRIGGER [schema_name.]trigger_name;
-- schema_name. 代表删除哪个数据库的触发器
update类型触发器的语法
CREATE TRIGGER tb_user_update_trigger
AFTER UPDATE ON tb_user FOR EACH ROW
INSERT INTO user_log(id,operation,operation_time,operation_id,operation_params)VALUES
(NULL,'update',NOW(),new.id,
CONCAT('插入的数据内容为: id=',old.id,',username=',old.username,',password=',old.password
' | 插入的数据内容为: id=',new.id,',username=',new.username,',password=',new.password));
END;
UPDATE tb_user SET username='heihei' WHERE id=1;
该触发器表示在向tb_user表中更新数据后触发该触发器,向日志表中插入更新操作日志
delete 类型触发器的语法
CREATE TRIGGER tb_user_delete_trigger
AFTER DELETE ON tb_user FOR EACH ROW
INSERT INTO user_log(id,operation,operation_time,operation_id,operation_params)VALUES
(NULL,'delete',NOW(),old.id,
CONCAT('删除数据内容为: id=',old.id,',username=',old.username,',password=',old.password));
END;
DELETE FROM tb_user WHERE id=1;
该触发器表示在向tb_user表中删除数据后触发该触发器,向日志表中插入删除的操作日志
qiumin