mysql 触发器语法与应用示例
本文实例讲述了mysql 触发器语法与应用。分享给大家供大家参考,具体如下:
例子:创建触发器,记录表的增、删、改操作记录
//创建user表; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `account` varchar(255) DEFAULT NULL, `name` varchar(255) DEFAULT NULL, `address` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; //创建对user表操作历史表 DROP TABLE IF EXISTS `user_history`; CREATE TABLE `user_history` ( `id` bigint(20) NOT NULL AUTO_INCREMENT, `user_id` bigint(20) NOT NULL, `operatetype` varchar(200) NOT NULL, `operatetime` datetime NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
DELIMITER:改变输入的结束符,默认情况下输入结束符是分号;,这里把它改成了两个分号;;,这样做的目的是把多条含分号的语句做个封装,全部输入完之后一起执行,而不是一遇到默认的分号结束符就自动执行;
- new:当触发插入和更新事件时可用,指向的是被操作的记录
- old: 当触发删除和更新事件时可用,指向的是被操作的记录
INSERT:
DROP TRIGGER IF EXISTS `tri_insert_user`; DELIMITER ;; CREATE TRIGGER `tri_insert_user` AFTER INSERT ON `user` FOR EACH ROW begin INSERT INTO user_history(user_id, operatetype, operatetime) VALUES (new.id, 'add a user', now()); end ;; DELIMITER ;
UPDATE:
DROP TRIGGER IF EXISTS `tri_update_user`; DELIMITER ;; CREATE TRIGGER `tri_update_user` AFTER UPDATE ON `user` FOR EACH ROW begin INSERT INTO user_history(user_id,operatetype, operatetime) VALUES (new.id, 'update a user', now()); end ;; DELIMITER ;
DELETE:
DROP TRIGGER IF EXISTS `tri_delete_user`; DELIMITER ;; CREATE TRIGGER `tri_delete_user` AFTER DELETE ON `user` FOR EACH ROW begin INSERT INTO user_history(user_id, operatetype, operatetime) VALUES (old.id, 'delete a user', now()); end ;; DELIMITER ;
更多关于MySQL相关内容感兴趣的读者可查看本站专题:《MySQL查询技巧大全》、《MySQL事务操作技巧汇总》、《MySQL存储过程技巧大全》、《MySQL数据库锁相关技巧汇总》及《MySQL常用函数大汇总》
希望本文所述对大家MySQL数据库计有所帮助。
相关推荐
zjuwangleicn 2020-06-25
debugjoker 2020-06-17
昊 2020-06-16
sunnyxuebuhui 2020-06-14
ncomoon 2020-06-14
hanshangzhi 2020-06-12
wudaokouer 2020-04-16
一昕之代码 2020-02-20
李轮清 2020-05-11
URML 2020-05-10
nimeijian 2020-05-06
lpfvip00 2020-04-26
lt云飞扬gt 2020-04-21
书弋江山 2020-04-19
dayi 2020-04-11
daillo 2020-04-07
Accpcjg 2020-03-05
勇往直前 2020-03-04