簡單的說,就是一張表發生了某件事(插入、刪除、更新操作),然後自動觸發了預先編寫好的若干條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';
增加程序的復雜度,有些業務邏輯在代碼中處理,有些業務邏輯用觸發器處理,會使後期維護變得困難;