逐步讲解MySQL中定时事件计划的创建_MySQL
一、使用过程
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

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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Big data structure processing skills: Chunking: Break down the data set and process it in chunks to reduce memory consumption. Generator: Generate data items one by one without loading the entire data set, suitable for unlimited data sets. Streaming: Read files or query results line by line, suitable for large files or remote data. External storage: For very large data sets, store the data in a database or NoSQL.

Backing up and restoring a MySQL database in PHP can be achieved by following these steps: Back up the database: Use the mysqldump command to dump the database into a SQL file. Restore database: Use the mysql command to restore the database from SQL files.

MySQL query performance can be optimized by building indexes that reduce lookup time from linear complexity to logarithmic complexity. Use PreparedStatements to prevent SQL injection and improve query performance. Limit query results and reduce the amount of data processed by the server. Optimize join queries, including using appropriate join types, creating indexes, and considering using subqueries. Analyze queries to identify bottlenecks; use caching to reduce database load; optimize PHP code to minimize overhead.

How to insert data into MySQL table? Connect to the database: Use mysqli to establish a connection to the database. Prepare the SQL query: Write an INSERT statement to specify the columns and values to be inserted. Execute query: Use the query() method to execute the insertion query. If successful, a confirmation message will be output.

To use MySQL stored procedures in PHP: Use PDO or the MySQLi extension to connect to a MySQL database. Prepare the statement to call the stored procedure. Execute the stored procedure. Process the result set (if the stored procedure returns results). Close the database connection.

Creating a MySQL table using PHP requires the following steps: Connect to the database. Create the database if it does not exist. Select a database. Create table. Execute the query. Close the connection.

One of the major changes introduced in MySQL 8.4 (the latest LTS release as of 2024) is that the "MySQL Native Password" plugin is no longer enabled by default. Further, MySQL 9.0 removes this plugin completely. This change affects PHP and other app

Oracle database and MySQL are both databases based on the relational model, but Oracle is superior in terms of compatibility, scalability, data types and security; while MySQL focuses on speed and flexibility and is more suitable for small to medium-sized data sets. . ① Oracle provides a wide range of data types, ② provides advanced security features, ③ is suitable for enterprise-level applications; ① MySQL supports NoSQL data types, ② has fewer security measures, and ③ is suitable for small to medium-sized applications.
