1. 為了測試觸發器和預存程序,首先建立一張簡單的表:
複製代碼 代碼如下:CREATE TABLE `airuser` (
`userId` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(128) NOT NULL,
PRIMARY KEY (`userId`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8
2. 為該表的插入操作,建立一張記錄表: 複製代碼 代碼如下:CREATE TABLE `airuser_record` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(45) DEFAULT NULL,
`edittime` timestamp NULL DEFAULT NULL,
`edittype` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
3. 編寫一個插入操作的觸發器: 複製代碼 代碼如下:DROP TRIGGER insert_trigger;
delimiter |
CREATE TRIGGER insert_trigger BEFORE INSERT ON airuser
FOR EACH ROW BEGIN
INSERT INTO airuser_record SET username = NEW.username, edittime=now(), edittype='insert';
END;
SHOW TRIGGERS;
4. 為批量插入編寫預存程序: 複製代碼 代碼如下:DROP procedure createUsers;
delimiter |
create procedure createUsers(IN count int)
begin
declare i int;
set i=0;
while i<count do
insert into airuser set username=concat('user_',i);
set i=i+1;
end while;
end;
show procedure status;
5. 調用預存程序,驗證預存程序是工作的,並驗證在插入記錄前,觸發器能正確被觸發: 複製代碼 代碼如下:call createUsers(10);
6. 最後通過插入記錄表再次驗證: 複製代碼 代碼如下:SELECT * FROM mars_jpa.airuser_record;