hanshangzhi 2020-06-14
本文实例讲述了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:改变输入的结束符,默认情况下输入结束符是分号;,这里把它改成了两个分号;;,这样做的目的是把多条含分号的语句做个封装,全部输入完之后一起执行,而不是一遇到默认的分号结束符就自动执行;
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数据库计有所帮助。