mysql日志触发器实现代码
程序员文章站
2022-07-09 13:52:29
sql语句drop triggerifexists sys_menu_edit;create trigger sys_menu_edit before update on sys_menu for e...
sql语句
drop trigger if exists sys_menu_edit; create trigger sys_menu_edit before update on sys_menu for each row begin insert into `g4m`.`sys_log` ( `table_name`, `val_id`, `data_json` ) values ( 'sys_menu', old.id, concat( "{", concat_ws( ',', concat_ws( old.id, '"id":"', '"' ), concat_ws( old.code, '"code":"', '"' ), concat_ws( old.type_dic, '"type_dic":"', '"' ), concat_ws( old.name, '"name":"', '"' ), concat_ws( old.pid, '"pid":"', '"' ), concat_ws( old.status_dic, '"status_dic":"', '"' ), concat_ws( old.url, '"url":"', '"' ), concat_ws( old.path, '"path":"', '"' ), concat_ws( old.icon, '"icon":"', '"' ), concat_ws( old.sort, '"sort":"', '"' ), concat_ws( old.remark, '"remark":"', '"' ), concat_ws( old.create_time, '"create_time":"', '"' ), concat_ws( old.modify_uer_id, '"modify_uer_id":"', '"' ), concat_ws( old.modify_time, '"modify_time":"', '"' ) ), "}" ) );
mysql用触发器实现日志记录
create trigger news_log after insert on news;
for each row insert into `news_logs` select *, now() from news where newsid = (select max(newsid ) from news);
drop trigger news_log ;
一共两个表,一个是原始表 news,一个是日志表news_logs(多了一列日期),可以实现新插入时自动记录日志,不用写代码了。 类似还可以实现更新时插入更新日志,详情可查看 mysql 的文档。
mysql 用触发器记录操作补充
mysql 不能在一个触发器中进行insert,update,delete操作,需分别建三个触发器
insert触发器:
delimiter $$ create trigger tri_city_insert after insert on t_xfw_city for each row begin insert into t_tri_city(id,name,provinceid,ctype) values(new.id,new.name,new.provinceid,1); end
update触发器:
delimiter $$ create trigger tri_city_update after update on t_xfw_city for each row begin insert into t_tri_city(id,name,provinceid,ctype) values(new.id,new.name,new.provinceid,2); end
delete触发器:
delimiter $$ create trigger tri_city_delete after delete on t_xfw_city for each row begin insert into t_tri_city(id,name,provinceid,ctype) values(old.id,old.name,old.provinceid,3); end
对一个表建三个触发器有些麻烦,不知道还有没有好点的方法