用mysql触发器实现log记录

时间:2022-04-24 12:31:21

首先建立两张测试用表

mysql> desc pay;
+-------+---------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------------+------+-----+---------+----------------+
| id | int() | NO | PRI | NULL | auto_increment |
| money | decimal(,) | NO | | NULL | |
| op | char() | YES | | NULL | |
+-------+---------------+------+-----+---------+----------------+
rows in set (0.00 sec) mysql> desc log;
+-------------+-----------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+-----------+------+-----+-------------------+-----------------------------+
| id | int() | NO | PRI | NULL | auto_increment |
| op | char() | YES | | NULL | |
| oid | int() | NO | | NULL | |
| last_update | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+-------------+-----------+------+-----+-------------------+-----------------------------+
rows in set (0.00 sec)

创建一个触发器

mysql> delimiter $$
mysql> create trigger pay_log after insert on pay for each row begin insert into log set oid=new.id, op=new.op; end;$$
mysql> delimiter ;

参看触发器是否创建成功

mysql> show triggers\G;
*************************** . row ***************************
Trigger: pay_log
Event: INSERT
Table: pay
Statement: begin insert into log set oid=new.id, op=new.op; end
Timing: AFTER
Created: NULL
sql_mode:
Definer: root@localhost
character_set_client: latin1
collation_connection: latin1_swedish_ci
Database Collation: utf8_general_ci
row in set (0.00 sec) ERROR:
No query specified

测试

mysql> insert into pay set money=,op='jimmy';
mysql> select * from pay;
+----+--------+-------+
| id | money | op |
+----+--------+-------+
| | 123.00 | jimmy |
| | 123.00 | jimmy |
+----+--------+-------+
rows in set (0.00 sec) mysql> select * from log;
+----+-------+-----+---------------------+
| id | op | oid | last_update |
+----+-------+-----+---------------------+
| | jimmy | | -- :: |
| | jimmy | | -- :: |
+----+-------+-----+---------------------+
rows in set (0.00 sec)

同理还可以再创建一个update和delete的触发器

题外话

创建触发器的时候发现没有权限,启动参数加上--skip-grant-table解决