zoukankan      html  css  js  c++  java
  • mysql event scheduler机制 与 动态表名创建

    今天有一个需求,需要定时在mysql创建表与删除表,以及根据日期命名表名。诚然,通过外部程序很容易实现与控制这一切。

    但是需要额外的服务需要维护,以及实现其它的调度机制。为了提高服务的稳定性,可维护性,所以打算研究一下mysql的event scheduler机制。

    在网上了解了一下这方面内容,非常杂乱。而且基本雷同。经过自己的摸索,终于实现。算是对其它文章的一个补充。

    方案如下:(mysql 5.1以后版本)

    1. 查看当前是否已开启event scheduler机制,检查方法:SHOW VARIABLES LIKE 'event_scheduler'; 如果显示的值为OFF,则首先需要开启。

    2. 开启方法: 修改 /etc/my.cnf 文件 

    [mysqld]
    添加 event_scheduler=ON

    3 . 重启 mysql  服务。

    4.  create event 语法:

    CREATE EVENT [IF NOT EXISTS] event_name
    ON SCHEDULE schedule
    [ON COMPLETION [NOT] PRESERVE]
    [ENABLE | DISABLE]
    [COMMENT 'comment']
    DO sql_statement;

    5.  范例:

    CREATE DEFINER = hotonline EVENT IF NOT EXISTS create_aronline_evnet

    ON SCHEDULE EVERY 1 DAY STARTS '2013-03-17 12:00:00'

    DO
    call create_aronline_procedure();

    其中 create_aronline_evnet 为 event 名称,建好以后可以去 mysql.event表查询。

           EVERY 1 DAY STARTS '2013-03-17 12:00:00' 为自从 2013-03-17 12:00:00  开始 每天运行一次。

          call create_aronline_procedure(); 为执行的一个存储过程。

    -------- 以上即为 event scheduler 的机制,具体语法请参考mysql 文档,或网上其它文档 --------------  

    6.  mysql 动态表名的实现:( 通过一般sql 是无法实现的,需要prepare支持,一下为存储过程封装的)

    delimiter $$
    create procedure create_aronline_procedure()
    begin
    set @prefix = 'CREATE TABLE IF NOT EXISTS ';
    set @tablename = CONCAT('ar_online_',date_format(date_add(now(), interval 1 day),'%Y_%m_%d'));
    set @suffix = '(id bigint(20) NOT NULL AUTO_INCREMENT,seed bigint(20) DEFAULT NULL,vid bigint(20) DEFAULT NULL,count int(11) NOT NULL,score double DEFAULT NULL,update_time timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,PRIMARY KEY (id),UNIQUE KEY pair (seed,vid)) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8';
    set @create_sql = concat(@prefix,@tablename,@suffix);
    prepare stmt from @create_sql;
    execute stmt;
    deallocate prepare stmt;
    end;
    $$
    delimiter ;

    核心语法为红色标注的。

    set @tablename = CONCAT('ar_online_',date_format(date_add(now(), interval 1 day),'%Y_%m_%d'));  这个部分为根据日期生成表名,然后concat.

    prepare stmt from @create_sql;   其中 stmt  为 prepare 的命名。

       

       

  • 相关阅读:
    [Tyvj模拟赛]运
    [NOIP 2011]聪明的质监员
    暑假集训D10总结
    暑假集训D9总结
    [POI2008]枪战Maf
    [Usaco2007 Open]Fliptile 翻格子游戏
    [bzoj1592] Making the Grade
    学生信息管理系统(增删改查)【代码不完整】
    《程序员修炼之道》第五次读后感
    《程序员修炼之道》第四次读后感
  • 原文地址:https://www.cnblogs.com/g4279/p/4345043.html
Copyright © 2011-2022 走看看