简单的说,就是一张表发生了某件事(插入、删除、更新操作),然后自动触发了预先编写好的若干条SQL语句的执行;
特点:触发事件的操作和触发器里的SQL语句是一个事务操作,具有原子性,要么全部执行,要么都不执行;
作用:保证数据的完整性,起到约束的作用;
接下来将创建user和user_history表,以及三个触发器tri_insert_user、tri_update_user、tri_delete_user,分别对应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;
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: 当触发删除和更新事件时可用,指向的是被操作的记录
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 ;
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 ;
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 ;
INSERT INTO user(account, name, address) VALUES (‘user1‘, ‘user1‘, ‘user1‘); INSERT INTO user(account, name, address) VALUES (‘user2‘, ‘user2‘, ‘user2‘); UPDATE user SET name = ‘user3‘, account = ‘user3‘, address=‘user3‘ where name=‘user1‘; DELETE FROM `user` where name = ‘user2‘;
增加程序的复杂度,有些业务逻辑在代码中处理,有些业务逻辑用触发器处理,会使后期维护变得困难;
原文:http://www.cnblogs.com/zyshi/p/6618839.html