How do I test mysql triggers and stored procedures

  • 2020-05-14 05:07:03
  • OfStack

1. To test the triggers and stored procedures, start with a simple table:
 
CREATE TABLE `airuser` ( 
`userId` int(11) NOT NULL AUTO_INCREMENT, 
`username` varchar(128) NOT NULL, 
PRIMARY KEY (`userId`) 
)ENGINE=InnoDB DEFAULT CHARSET=utf8 

2. For the insert operation of the table, create a record table:
 
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. Write a trigger for an insert operation:
 
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. Write stored procedures for bulk inserts:
 
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 the stored procedure, verify that the stored procedure is working, and verify that the trigger is properly triggered before inserting the record:
 
call createUsers(10); 

6. Finally, verify again by inserting the record table:
 
SELECT * FROM mars_jpa.airuser_record; 

Related articles: