How to run a MySQL query on every service start?

1.1k Views Asked by At

I need to run a query to populate a memory table on every MySQL start.

Is there any way to do this?

2

There are 2 best solutions below

0
On BEST ANSWER

MySQL is able to read statements from init_file on startup.

You'd have to place the following in my.ini or my.cnf (depending on the OS) file

[mysqld] 
init-file="/path/to/your/query/populate_memory_table.sql"
0
On

Another option is to have a system script run after mysql starts. With systemd in Linux, the following would work:

cat > /lib/systemd/system/mysql-preload.service << END
[Unit]
Description=Pre-Load MEMORY tables after MySQL starts
PartOf=mysql.service
After=mysql.service

[Service]
Type=oneshot
ExecStart=/home/myuser/script.sh

[Install]
WantedBy=multi-user.target

END
systemctl daemon-reload

The script will be run the next time mysql starts or restarts. Not quite as good as init_file because mysql will be available for queries before the MEMORY tables have been populated, but much more flexible.