java程式建立mysql觸發器
最近在工作中要動態的建立表和相應的觸發器,特此記錄下。
1.使用SQL建立觸發器
DELIMITER $$
CREATE TRIGGER `catefiles_trigger` AFTER INSERT ON `catefiles` FOR EACH ROW
begin
declare num1 int;
set num1 = (select num from est_client_catescan_status where
cateid=new.cateId and taskid=new.taskId and clientid=new.clientId);
if(num1>=0) then
update catescan_status set num=num1+1 where cateid=new.cateId and taskid=new.taskId and clientid=new.clientId;
else
insert catescan_status(cateid,num,status,taskid,clientid) values(new.cateId,1,0,new.taskid,new.clientId);
end if;
end$$
2.在java程式裡建立觸發器
String sql=+" CREATE TRIGGER catefiles_trigger AFTER INSERT ON catefiles FOR EACH ROW"
+" begin"
+" declare scannum int;"
+" set scannum = (select num from est_client_catescan_status where"
+" cateid=new.cateId and taskid=new.taskId and clientid=new.clientId);"
+" if(scannum>=0) then"
+" update catescan_status set num=scannum+1 where cateid=new.cateId and taskid=new.taskId and clientid=new.clientId;"
+" else"
+" insert catescan_status(cateid,num,status,taskid,clientid) values(new.cateId,1,0,new.taskid,new.clientId);"
+" end if;"
+" end";
Connection con = DbConnectionManager.getConnection();
PreparedStatement
pstmt.execute();
3.可以看出區別:在java中建立觸發器,不需要限定符DELIMITER ,加上的話執行過程中會報mysql語法錯誤。