导出数据库
将指定数据库实例(MYSQL_HOST、MYSQL_PORT、MYSQL_USER、MYSQL_PASSWORD)
中的所有数据库(表结构、数据)导出到指定目录(BACKUP_DIR)下
的多个单独的SQL脚本,每个SQL脚本名称即为数据库名(如my_db.sql脚本的数据库名为my_db),且排除内置的mysql、sys、information_schema、performance_schema数据库,具体导出脚本backup.sh内容如下:
#!/bin/bash# MySQL credentials
MYSQL_USER="root"
MYSQL_PASSWORD="myPassw"
MYSQL_HOST="127.0.0.1"
MYSQL_PORT="3306"# Directory for backups
BACKUP_DIR="backup-dir"# Create backup directory if it doesn't exist
mkdir -p "$BACKUP_DIR"# Loop through each database and back it up
for db in $(mysql -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -P "$MYSQL_PORT" -e 'SHOW DATABASES;' | grep -Ev 'Database|mysql|sys|information_schema|performance_schema'); doecho "$BACKUP_DIR/$db.sql"mysqldump -h "$MYSQL_HOST" -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -P "$MYSQL_PORT" "$db" > "$BACKUP_DIR/$db.sql"
done
导入数据库
将备份目录(SQL_DIR)下的多个sql脚本恢复到指定数据库实例(MYSQL_HOST、MYSQL_PORT、MYSQL_USER、MYSQL_PASSWORD)
中,每个sql脚本名称即为数据库名(如my_db.sql脚本的数据库名为my_db),批量建库、导入SQL脚本的restore.sh内容如下:
#!/bin/bash# MySQL credentials
MYSQL_USER="root"
MYSQL_PASSWORD="myPassw"
MYSQL_HOST="127.0.0.1"
MYSQL_PORT="33306"# Directory containing SQL scripts
SQL_DIR="backup-dir"# Loop through each SQL file in the directory
for sql_file in "$SQL_DIR"/*.sql; do# Extract the database name from the file namedb_name=$(basename "$sql_file" .sql)# Create the database with specified character set and collationecho "Creating database: $db_name"mysql -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -h "$MYSQL_HOST" -P "$MYSQL_PORT" -e "CREATE DATABASE IF NOT EXISTS \`$db_name\` CHARACTER SET 'utf8mb4' COLLATE 'utf8mb4_general_ci';"# Import the SQL file into the databaseecho "Importing data into database: $db_name"mysql -u "$MYSQL_USER" -p"$MYSQL_PASSWORD" -h "$MYSQL_HOST" -P "$MYSQL_PORT" "$db_name" < "$sql_file"
doneecho "All databases created and data imported successfully."