zoukankan      html  css  js  c++  java
  • MySQL中存储过程+事件的使用方法

    一、背景

    将界面操作日志存储在MySQL数据库中的operationlog表中,如果该表不能自动备份,表中的数据会越来越多,影响速度。可以定期将表中数据备份到另外一个表中来解决。

    二、解决方案

    1、使用MySQL中的存储过程+事件解决。

      存储过程逻辑为:

      1)创建一个新表operationlog_temp,各字段同operationlog相同;

      2)将表operationlog更名为operationlog_yyyy-mm-dd;

      3)将表operationlog_temp更名为operationlog

      事件逻辑为:

      1)每个3个月定时调用一次存储过程bakOpLog

    2、定义存储过程bakOpLog:

    【注】
    开始事件功能(MySQL必须先开启事件功能,才能使用事件),用如下SQL语句
    SHOW VARIABLES LIKE 'event_scheduler';
    SET GLOBAL event_scheduler = ON;

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    CREATE DEFINER=`sa`@`%` PROCEDURE `bakOpLog`()
    BEGIN
    create table operationlog_temp like operationlog;
    set @i=current_date();
    --执行rename table operationlog to operationlog_yyyy-mm-dd
    set @sqlstr=CONCAT('rename table operationlog to `operationlog_',cast(@i as char),'`');
    select @sqlstr;
    PREPARE renameOpLog FROM @sqlstr;
    EXECUTE renameOpLog;
    rename table operationlog_temp to operationlog;
    END;

    3、定义事件callProcedureBakOpLog

    1
    CREATE DEFINER=`sa`@`%` EVENT `callProcedureBakOpLog` ON SCHEDULE EVERY 1 DAY STARTS '2014-12-30 00:00:00' ENDS '2015-01-06 00:00:00' ON COMPLETION PRESERVE ENABLE DO call bakOpLog();

    4、存储过程用到的一些语法

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    set @i=current_date();  //将全局变量i赋值为当前日期
    set @sqlstr=CONCAT('rename table operationlog to `operationlog_',cast(@i as char),'`'); //sqlstr=rename table operationlog to operationlog_yyyy-mm-dd
    PREPARE renameOpLog FROM @sqlstr;   //定义预处理语句
    EXECUTE renameOpLog;    //执行预处理语句
     
    查看创建的事件
    SHOW EVENTS;
    也可以在mysql库中产看event表
     
    1) 临时关闭事件
    ALTER EVENT e_test DISABLE;
    2) 开启事件
    ALTER EVENT e_test ENABLE;
    3) 将每天清空test表改为5天清空一次:
    ALTER EVENT e_test
    ON SCHEDULE EVERY 5 DAY;
    4) 删除事件(DROP EVENT)
    DROP EVENT [IF EXISTS] event_name
    例如删除前面创建的e_test事件
    DROP EVENT e_test;
    当然前提是这个事件存在,否则会产生ERROR 1513 (HY000): Unknown event错误,因此最好加上IF EXISTS
    DROP EVENT IF EXISTS e_test;

    5、使用MySQL管理工具MySQL-Front操作存储过程、事件的简介操作

      1)定义存储过程、事件

      

      2)直接在mysql库中查看event表,该表中有定义过的事件

       

  • 相关阅读:
    gvim e303 无法打开 “[未命名]“的交换文件,恢复将不可能
    AspectJ获取方法注解的信息
    type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds int,java.lang.Object
    MySQL@淘宝 资料分享
    MySQL的语句执行顺序
    关于HttpClient上传中文乱码的解决办法
    使用IntelliJ IDEA查看类的继承关系图形
    javax.net.ssl.SSLException: Certificate doesn't match any of the subject alternative names
    Failed to process import candidates for configuration class [com.simple.....]
    安装npm及cnpm(Windows)
  • 原文地址:https://www.cnblogs.com/hanlong/p/5715577.html
Copyright © 2011-2022 走看看