一、使用过程
1.查看当前是否已开启事件计划(调度器)有3种方法:
SHOW VARIABLES LIKE 'event_scheduler'; SELECT @@event_scheduler; SHOW PROCESSLIST;
2. 开启事件计划(调度器)开关有4种方法:
SET GLOBAL event_scheduler = 1; SET @@global.event_scheduler = 1; SET GLOBAL event_scheduler = ON; SET @@global.event_scheduler = ON;
键值1或者ON表示开启;0或者OFF表示关闭;
3.关于事件计划的权限:
单独使用event调用SQL语句时,查看和创建需要用户具有event权限,调用该SQL语句时,需要用户具有执行该SQL的权限。Event权 限的设置保存在mysql.user表和mysql.db表的Event_priv字段中。(FLUSH PRIVILEGES;)
当event和procedure配合使用的时候,查看和创建存储过程需要用户具有create routine权限,调用存储过程执行时需要使用excute权限,存储过程调用具体的SQL语句时,需要用户具有执行该SQL的权限。
SELECT HOST,USER,Event_priv FROM mysql.user;
获取当前登陆的用户和数据库:SELECT CURRENT_USER(), SCHEMA();
从Figure1可以知道bfsql@%是没有Event_priv权限的,在该用户下创建事件的时候会出现下面的错误:
Error Code: 1044Access denied for user 'bfsql'@'%' to database 'blog'
如果出现上面的错误,执行下面的SQL就可以给bfsql@%赋予创建Event的权限:
UPDATE mysql.user SET Event_priv = 'Y' WHERE HOST='%' AND USER='bfsql'; FLUSH PRIVILEGES;
最后,你可以通过SHOW GRANTS FOR 'bfsql'@'%';查看所有权限;
4.创建事件:
(1)创建事件的语法如下:
CREATE EVENT [IF NOT EXISTS] event_name ON SCHEDULE schedule [ON COMPLETION [NOT] PRESERVE] [ENABLE | DISABLE] [COMMENT 'comment'] DO sql_statement
(2)创建事件的示例如下:
DELIMITER $$ CREATE EVENT IF NOT EXISTS e_blog ON SCHEDULE EVERY 30 SECOND ON COMPLETION PRESERVE DO BEGIN CALL MoveBlogData(); END$$ DELIMITER ;
DO sql_statement字段表示该event需要执行的SQL语句或存储过程。这里的SQL语句可以是复合语句,使用BEGIN和END标识符将复合SQL语句按照执行顺序放在之间。
--从现在开始每隔九天定时执行 CREATE EVENT EVENT1 ON SCHEDULE EVERY 9 DAY STARTS NOW() ON COMPLETION PRESERVE ENABLE DO BEGIN CALL TOTAL(); END --每个月的一号凌晨1 点执行 CREATE EVENT EVENT2 ON SCHEDULE EVERY 1 MONTH STARTS DATE_ADD(DATE_ADD(DATE_SUB(CURDATE(),INTERVAL DAY(CURDATE())-1 DAY), INTERVAL 1 MONTH),INTERVAL 1 HOUR) ON COMPLETION PRESERVE ENABLE DO BEGIN CALL STAT(); END ---每个季度一号的凌晨2点执行 CREATE EVENT TOTAL_SEASON_EVENT ON SCHEDULE EVERY 1 QUARTER STARTS DATE_ADD(DATE_ADD(DATE( CONCAT(YEAR(CURDATE()),'-',ELT(QUARTER(CURDATE()),1,4,7,10),'-',1)),INTERVAL 1 QUARTER),INTERVAL 2 HOUR) ON COMPLETION PRESERVE ENABLE DO BEGIN CALL SEASON_STAT(); END --每年1月1号凌晨四点执行 CREATE EVENT TOTAL_YEAR_EVENT ON SCHEDULE EVERY 1 YEAR STARTS DATE_ADD(DATE(CONCAT(YEAR(CURDATE()) + 1,'-',1,'-',1)),INTERVAL 4 HOUR) ON COMPLETION PRESERVE ENABLE DO BEGIN CALL YEAR_STAT(); END
5.事件开启与关闭:
开启某事件:
ALTER EVENT e_test ON COMPLETION PRESERVE ENABLE;
关闭某事件:
ALTER EVENT e_test ON COMPLETION PRESERVE DISABLE;
二、实例:
mysql定时器是系统给提供了event,而oracle里面的定时器是系统给提供的job。废话少说,下面创建表:
create table mytable ( id int auto_increment not null, name varchar(100) not null default '', introduce text not null, createtime timestamp not null, constraint pk_mytable primary key(id) )
创建存储过程,这里的存储过程主要提供给mysql的定时器event来调用去执行:
create procedure mypro() BEGIN insert into mytable (name,introduce,createtime) values ('1111','inner mongolia',now()); end;
这里只是简单的写了一下,只是为了说明例子。
紧接着创建mysql的定时器event:
create event if not exists eventJob on schedule every 1 second on completion PRESERVE do call mypro();
这里设置为每一秒执行一次
至此所有的准备工作已经写完了,做完这些,mysql要想利用定时器必须的做准备工作,就是把mysql的定时器给开启了:
SET GLOBAL event_scheduler = 1; -- 启动定时器 SET GLOBAL event_scheduler = 0; -- 停止定时器
紧接着还要开启事件:
ALTER EVENT eventJob ON COMPLETION PRESERVE ENABLE; -- 开启事件 ALTER EVENT eventJob ON COMPLETION PRESERVE DISABLE; -- 关闭事件 SHOW VARIABLES LIKE '%sche%'; -- 查看定时器状态
至此,你去数据库里面的表mytable里面看下,系统会每隔一秒去插入一条数据,嘻嘻,任务完成了。
select * from mytable

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1
Powerful PHP integrated development environment
