Overview:
- It is a common programming task to schedule an action to occur once or several times in the future.
- In MySQL server too events can be scheduled to perform tasks like incrementing a counter, updating a set of columns in a database table, deleting a set of rows from a table and so on.
- Events can be scheduled in MySQL Server using the SQL Statement CREATE EVENT.
- An event in MySQL Server can be scheduled for only once at a specific time or several times upon expiry of a time interval.
- To create an event the user should have the EVENT privilege on the database.
- For the event to be executed the thread Event Scheduler should be running.
Scheduling an Event in MySQL from a Python Program:
- Import the PyMySQL module and create a connection object to the MySQL database.
- Obtain a cursor object and execute the CREATE EVENT statement, which will schedule an event.
Example:
# ----- Example Python program to schedule an event in MySQL server ----- import pymysql # Method that returns a connection to the MySQL Server # DB connection parameters # Connect to MySQL database server try: # SQL statement to create an event in MySQL # Execute the SQL statement sqlShowEvents = "SHOW EVENTS FROM test" # Fetch all the rows except Exception as e: finally: |
Output:
List of events: {'Db': 'test', 'Name': 'StatusUpdate', 'Definer': 'root@localhost', 'Time zone': 'SYSTEM', 'Type': 'RECURRING', 'Execute at': None, 'Interval value': '1', 'Interval field': 'HOUR', 'Starts': datetime.datetime(2019, 6, 19, 1, 40, 50), 'Ends': None, 'Status': 'ENABLED', 'Originator': 0, 'character_set_client': 'utf8mb4', 'collation_connection': 'utf8mb4_unicode_ci', 'Database Collation': 'latin1_swedish_ci'} |