2019年2月10日更新。
使用mysqldump实现导出sql语句文件的两个不同系统的备份脚本。
Windows .bat脚本
/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/*/* @echo off echo. echo MySQL数据库备份 echo ***************************** echo. echo 今天是 %date% echo 时间是 %time% echo. echo ***************************** set "Ymd=%date:~,4%%date:~5,2%%date:~8,2%" md "D:\JDBC\%Ymd%" "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqldump" --opt -Q -uroot -pabc123 --default-character-set=latin1 test > "D:\JDBC\%Ymd%\test_bak.sql" echo. echo MySQL数据库备份完成,请进行检查。。。 echo. echo. pause
Linux .sh脚本
#!/bin/sh
# Database info
DB_USER="dumper"
DB_PASS="..."
DB_HOST="..."
# Database array
DB_NAME=("hotel" "food" "foodweb")
# Others vars
BIN_DIR="/usr/bin" #the mysql bin path
BCK_DIR="/home/mysql-backups" #the backup file directory
DATE=`date +%F`
# create file
mkdir $BCK_DIR/$DATE
# TODO
# /usr/bin/mysqldump --opt -ubatsing -pbatsingpw -hlocalhost timepusher > /mnt/mysqlBackup/db_`date +%F`.sql
for var in ${DB_NAME[@]};
do
$BIN_DIR/mysqldump --opt --single-transaction --master-data=2 -u$DB_USER -p$DB_PASS -h$DB_HOST $DB_NAME > $BCK_DIR/$DATE/db_$var.sql
done
参数说明:
--master-data[=#],在备份导出的文件里追加二进制binlog文件的位置和名称。
- 如果值等于1,就会添加一个CHANGE MASTER语句
- 如果值等于2,就会在CHAGE MASTER语句前添加注释
这个参数会--lock-all-tables锁表,除非你指定了--single-transaction 。这种情况下,锁表只会在dump开始的时候持续一小段时间,照理说 在dump的时候,任何动作都会影响到binlog文件 dump结束之后,选项会自动关闭锁表功能。
加入计划任务
crontab -e 0 0 * * * /home/sh/mysql-backups/dump.sh
Mysql5.6以上版本会出现一段提示 mysqldump: [Warning] Using a password on the command line interface can be insecure. (阅读:6.1.2.1 End-User Guidelines for Password Security),在更高的版本里,mysql为了确保自身的安全是禁止在cli模式下直接使用明文密码的,这个新的限制在执行mysql -u -p时,也是一样的。

我们需要将密码存放在一个文件里,比如a.cnf或者abc.txt,也可以放在mysql的my.cnf里。
Store your password in an option file. For example, on Unix, you can list your password in the [client] section of the .my.cnf file in your home directory:
[client] password=your_passTo keep the password safe, the file should not be accessible to anyone but yourself. To ensure this, set the file access mode to 400 or 600. For example:
chmod 600 .my.cnf
接着执行我们的sh脚本就要修改成如下:
#!/bin/sh
# Database info
DB_USER="dumper"
DB_PASS="..."
DB_HOST="..."
# Database array
DB_NAME=("hotel" "food" "foodweb")
# Others vars
BIN_DIR="/usr/bin" #the mysql bin path
BCK_DIR="/home/mysql-backups" #the backup file directory
DATE=`date +%F`
# create file
mkdir $BCK_DIR/$DATE
for var in ${DB_NAME[@]};
do
$BIN_DIR/mysqldump --opt --single-transaction --master-data=2 --defaults-extra-file=/etc/my.cnf $DB_NAME > $BCK_DIR/$DATE/db_$var.sql
done
如果出现错误mysqldump: [ERROR] unknown variable 'defaults-extra-file=/etc/my.cnf ,则用 --defaults-file。

发表回复