對於linux系統下的mysql DB的數據備份,如下兩種方法,第一種方法是隻備份數據,將數據保存在文本文件中;第二種方法是將整個DB備份,生成SQL文件,在DB恢復時較方便,固然,若是須要,也能夠對個別表進行備份。
方法一:
mysql
#!/bin/bash #DB服務器IP DB_HOST="127.0.0.1" #database name DB_NAME="mysql" #database username DB_USER="USER" #database password DB_PASS="password" #須要備份的表名 TBL_NAME_1=user #須要備份的表名 TBL_NAME_2=db #當前日期時間字符串 例:2010-12-20-10-12-30 (年月日時分秒) DATE=`date +%Y-%m-%d-%H-%M-%S` #執行mysql命令的參數 SQL_OPT="-u$DB_USER -p$DB_PASS -h $DB_HOST $DB_NAME" /usr/bin/mysql $SQL_OPT << EOF #將單個表的數據導出到文件中, #FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' 這些選項是把數據用逗號分隔,雙引號引發來,換行用\n;若是不用,能夠將這些選項刪除。 select * from $TBL_NAME_1 into outfile "/tmp/bakfile/$TBL_NAME_1.$DATE.txt" FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'; select * from $TBL_NAME_2 into outfile "/tmp/bakfile/$TBL_NAME_2.$DATE.txt" FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'; quit EOF echo 'Backup success'
方法二:
linux
#!/bin/bash #DB服務器IP DB_HOST="127.0.0.1" #database name DB_NAME="mysql" #database username DB_USER="USER" #database password DB_PASS="password" #當前日期時間字符串 例:2010-12-20-10-12-30 (年月日時分秒) DATE=`date +%Y-%m-%d-%H-%M-%S` #bakup file absolute path BAKUP_FILE=/tmp/bakfile/$DB_NAME-$DATE.sql #執行mysqldump命令的參數 SQL_OPT="-u$DB_USER -p$DB_PASS -h $DB_HOST $DB_NAME" #執行備份,整個DB全部表的備份,SQL語句的形式 /usr/bin/mysqldump --opt $SQL_OPT > $BAKUP_FILE echo 'Backup success。'