MySQL中的触发器
1.触发器
简单的说就是一张表在发生某件事时(增删改),然后会自动的触发预先编写好的若干条SQL语句的执行。
2.特点
触发事件的操作和触发器里的SQL语句都是一个事务操作,具有原子性,要么全部执行,要么都不执行。
Demo
创建user和user_history表,以及三个触发器his_insert_user、his_update_user、his_delete_user,分别对应user表的增、删、改三件事件;
SQL语句
创建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_history表
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;
触发器
Navicat下新建触发器
在你的数据库里找到user表,然后设计表。
user表.png
然后找到触发器,如下图所示:
新增
his_insert_user.png修改
his_update_user.png删除
his_delete_user.png测试
INSERT INTO user(account, name, address) VALUES ('xxl', 'sss', 'aaa');
-- UPDATE user SET name = 'bol', account = 'shakalaka', address='boom' where name='xxl';
-- DELETE FROM `user` where name = 'user1';
使用语句新建触发器
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 ;
说明:
new:当触发插入和更新事件时可用,指向的是被操作的记录
old: 当触发删除和更新事件时可用,指向的是被操作的记录
网友评论