How to configure scheduled database backups and restoration in MySQL?

MySQL database backup and restoration can be achieved using the built-in tools mysqldump and mysql. Below are the specific configuration steps:

  1. Scheduled database backups:
    You can use crontab to schedule the execution of the backup script. First, create a backup script such as backup.sh, and add the following content:
#!/bin/bash

# 设置备份文件存放目录
backup_dir="/path/to/backup"

# 设置数据库用户名和密码
db_user="username"
db_password="password"

# 设置数据库名
db_name="database_name"

# 设置备份文件名
backup_file="$backup_dir/$db_name-$(date +"%Y-%m-%d").sql"

# 使用mysqldump命令备份数据库
mysqldump -u $db_user -p$db_password $db_name > $backup_file

Then use crontab to schedule the backup script to run at a specific time, for example, at 3 AM every day.

0 3 * * * /path/to/backup.sh
  1. Restore database:
    To restore the database, you can use the mysql command to execute the backup file. First, copy the backup file to the server, and then execute the following command to restore the database:
mysql -u username -p password database_name < /path/to/backup.sql

The above are the configuration steps for scheduled backup and restoration of MySQL databases, hope it helps you.

bannerAds