一、查询数据库事件模式是否开启
SHOW VARIABLES LIKE 'event_scheduler';
二、设置开启/关闭事件
SET GLOBAL event_scheduler = ON;//开启
SET GLOBAL event_scheduler = OFF;//关闭
三、Mysql事件的语法简介
1、创建事件的语法
CREATE
[DEFINER = { user | CURRENT_USER }]
EVENT
[IF NOT EXISTS]
event_name
ON SCHEDULE
[ON COMPLETION [NOT] PRESERVE]
[ENABLE | DISABLE | DISABLE ON SLAVE]
[COMMENT 'comment']
DO event_body;
schedule:
AT timestamp [+ INTERVAL interval] ...
| EVERY interval
[STARTS timestamp [+ INTERVAL interval] ...]
[ENDS timestamp [+ INTERVAL interval] ...]
interval:
quantity {YEAR | QUARTER | MONTH | DAY | HOUR | MINUTE |
WEEK | SECOND | YEAR_MONTH | DAY_HOUR |
DAY_MINUTE |DAY_SECOND | HOUR_MINUTE |
HOUR_SECOND | MINUTE_SECOND}
2、 更改事件的语法
ALTER
[DEFINER = { user | CURRENT_USER }]
EVENT event_name
[ON SCHEDULE schedule]
[ON COMPLETION [NOT] PRESERVE]
[RENAME TO new_event_name]
[ENABLE | DISABLE | DISABLE ON SLAVE]
[COMMENT 'comment']
[DO event_body]
3、删除事件的语法
DROP EVENT [IF EXISTS] event_name
四、 Mysql 事件实战
CREATE TABLE `test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`t1` datetime DEFAULT NULL,
`id2` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=106 DEFAULT CHARSET=utf8
1、创建一个每隔3秒往test表中插入一条数据的事件
CREATE EVENT IF NOT EXISTS test ON SCHEDULE EVERY 3 SECOND
ON COMPLETION PRESERVE
DO INSERT INTO test(id,t1) VALUES('',NOW());
2、创建一个10分钟后清空test表数据的事件
CREATE EVENT IF NOT EXISTS test
ON SCHEDULE
AT CURRENT_TIMESTAMP + INTERVAL 1 MINUTE
DO TRUNCATE TABLE test.aaa;
3、创建一个在2012-08-23 00:00:00时刻清空test表数据的事件
CREATE EVENT IF NOT EXISTS test
ON SCHEDULE
AT TIMESTAMP '2012-08-23 00:00:00'
DO TRUNCATE TABLE test;
4、创建一个从2012年8月22日21点45分开始到10分钟后结束,
运行每隔3秒往test表中插入一条数据的事件
CREATE EVENT IF NOT EXISTS test ON SCHEDULE EVERY 3 SECOND
STARTS '2012-08-22 21:49:00'
ENDS '2012-08-22 21:49:00'+ INTERVAL 10 MINUTE
ON COMPLETION PRESERVE
DO INSERT INTO test(id,t1) VALUES('',NOW());
5、6、事件设置2012-08-22 00:00:00时刻开始运行,每隔1调用一次存储过程
CREATE EVENT test ON SCHEDULE EVERY 1 DAY
STARTS '2012-08-22 00:00:00'
ENDS '2012-08-22 00:00:00'+INTERVAL 40 DAY
ON COMPLETION PRESERVE DO
CALL test_add();