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;