1,触发器是由MYSQL的基本命令事件来触发某种特定操作,
触发器有两个重要因素:一是Action(动作)二是Condition(条件)
触发器就是在满足Conditoin条件时执行相应的动作,这个动作就是一系列的SQL语句
2,创建触发器
1 mysql> create trigger autolog before insert
2 -> on user for each row
3 -> insert into logtime values(null,now());
4 -> //
5 Query OK, 0 rows affected (0.12 sec)
6
7 mysql> insert into user values(null,'123','123',now())//
8 Query OK, 1 row affected (0.06 sec)
9
10 mysql> select * from logtime;
11 -> //
12 +----+---------------------+
13 id savetime
14 +----+---------------------+
15 1 2012-11-05 18:35:02
16 +----+---------------------+
17 1 row in set (0.00 sec)
创建触发器用的关键字是 trigger
autolog是触发器的名字
before insert 是在插入数据动作之前执行触发器before可以换成after,表明在之后执行动作
on user 表明触发器监听表格
each row 就是监听user表的每一列
user表格如果发生插入操纵的话,就会执行相应的动作
下面的一个SQL语句表明要执行的动作
第二个SQL语句是往user表里插入数据,然后查询logtime表,自动加入了一条记录
3,查看所有的触发器
18 mysql> show triggers
19 -> //
20 +---------+--------+-------+----------------------------------------+--------+---------+------------
21 ----------------------------------------------------+----------------+----------------------+-------
22 ---------------+--------------------+
23 Trigger Event Table Statement Timing Created sql_mode
24 Definer character_set_client collat
25 ion_connection Database Collation
26 +---------+--------+-------+----------------------------------------+--------+---------+------------
27 ----------------------------------------------------+----------------+----------------------+-------
28 ---------------+--------------------+
29 autolog INSERT user insert into logtime values(null,now()) BEFORE NULL STRICT_TRAN
30 S_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION root@localhost utf8 utf8_g
31 eneral_ci utf8_general_ci
32 +---------+--------+-------+----------------------------------------+--------+---------+------------
33 ----------------------------------------------------+----------------+----------------------+-------
34 ---------------+--------------------+
35 1 row in set (0.01 sec)
4,删除触发器
36 mysql> drop trigger autolog//
37 Query OK, 0 rows affected (0.01 sec)
本文出自 “Kenan_ITBlog” 博客,请务必保留此出处http://soukenan.blog.51cto.com/5130995/1050810
该贴被eink编辑于2012-11-19 10:49:30