网络安全 频道

妙用触发器有效的管理 MySQL数据库

实现中的例子用触发器审计记录,既然你了解了触发器的基本原理,让我们来看一个稍稍复杂的例子。我们常用触发器来建立一个自动“审计记录”,以记录各种用户对数据库的更改。为了解审计记录的实际应用,请看下面的表格(表格名:accounts),它列出了一个用户的三个银行账户余额。

mysql> SELECT * FROM accounts;



+----+------------+---------+



| id | label| balance |



+----+------------+---------+



|1 | Savings #1 |500 |



|2 | Current #1 |2000 |



|3 | Current #2 |3500 |



+----+------------+---------+



3 rows in set (0.00 sec)

然后,检查触发器是否被激活:

mysql> SHOW TRIGGERS \G



*************************** 1. row ***************************



?Trigger: t1



?Event: UPDATE



?Table: accounts



Statement: INSERT INTO audit (id, balance, user, time) 

VALUES (OLD.id, NEW.balance, CURRENT_USER(), NOW())



Timing: AFTER



?Created: NULL



Sql_mode:



1 row in set (0.01 sec)

再来看最后的结果:

mysql> UPDATE accounts SET balance = 500 WHERE id = 1;



Query OK, 1 row affected (0.00 sec)



Rows matched: 1?Changed: 1?Warnings: 0



mysql> UPDATE accounts SET balance = 900 WHERE id = 3;



Query OK, 1 row affected (0.01 sec)



Rows matched: 1?Changed: 1?Warnings: 0



mysql> UPDATE accounts SET balance = 1900 WHERE id = 1;



Query OK, 1 row affected (0.00 sec)



Rows matched: 1?Changed: 1?Warnings: 0

注意,对accounts表格所作的改变已被记录到audit表格中,将来如果出现问题,我们可以方便地从中进行恢复。

mysql> SELECT * FROM audit;



+------+---------+----------------+---------------------+



| id| balance | user| time|



+------+---------+----------------+---------------------+



|1 |500 | root@localhost | 2006-04-22 12:52:15 |



|3 |900 | root@localhost | 2006-04-22 12:53:15 |



|1 |1900 | root@localhost | 2006-04-22 12:53:23 |



+------+---------+----------------+---------------------+



3 rows in set (0.00 sec)

如上面的例子所示,触发器是一个强大的新功能,它大大增强了RDBMS的自动化程度。自己去试验,练习吧!

0
相关文章