CentOS下如何從MySQL全備文件中恢復(fù)單個(gè)庫或者單個(gè)表
2017-12-16 22:52:05
12980
在MySQL dba的日常實(shí)際工作中,一個(gè)實(shí)例下有多個(gè)庫,而我們常見的備份就是全庫備份。那么問題就來了,如果需要恢復(fù)單個(gè)庫或者單個(gè)表,怎么辦了,網(wǎng)上有很多人都有多種方法,今天,我自己結(jié)合眾多資料,將實(shí)踐記錄下來,以便供參考。
基本情況介紹:
MySQL版本:mysql-5.5.36.tar.gz
操作系統(tǒng):CentOS release 6.8 x64 (Final)
一、全庫備份

[root@pre ~]# cat backup.sh
#!/bin/bash/home/mysql/mysql55_3310/bin/mysqldump --defaults-file=/usr/local/local.cnf -E --triggers -e --max_allowed_packet=16777216 --net_buffer_length=16384 --master-data=2 --single-transaction --all-databases --quick | gzip >/home/dbbackup/all_database_bak_471_`date +%Y-%m-%d_%H_%M_%S`.sql.gz[root@pre ~]# cat /usr/local/local.cnf
[client]host=localhost
port=3310user=root
password=123456socket=/home/mysql/mysql55_3310/data/mysql.sock[root@pre ~]# sh backup.sh
二、顯示當(dāng)前庫

mysql> show databases;+--------------------+| Database |+--------------------+| information_schema || db_log || db_users || mysql || performance_schema |+--------------------+5 rows in set (0.00 sec)
mysql> use db_log;Database changed
mysql> show tables;
Empty set (0.00 sec)
三、現(xiàn)在從全備文件中恢復(fù)db_log單個(gè)庫
# 從全備份文件中將需要的庫的建表語句和INSERT數(shù)據(jù)拿出來,然后再導(dǎo)入

[root@pre ~]# sed -n '/^-- Current Database: `db_log`/,/^-- Current Database: `/p' all_database_bak_471_2017-12-04_15_36_38.sql > db_log.sql &# 導(dǎo)入庫中[root@pre ~]# /home/mysql/mysql55_3310/bin/mysql -uroot -p < db_log.sql &mysql> use db_log;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -ADatabase changed
mysql> show tables;+------------------------+| Tables_in_db_log |+------------------------+| api_online_logs || onlinegame || onlinegame_gamestats || onlinegame_playerstats || onlinegame_type || osa_menu_url || osa_module || osa_quick_note || osa_sys_log || osa_system || osa_user || osa_user_group || sample || user_online || user_psw_audit |+------------------------+15 rows in set (0.00 sec)
mysql> # 數(shù)據(jù)已經(jīng)恢復(fù)了
四、現(xiàn)在模擬恢復(fù)單個(gè)表的數(shù)據(jù)
# 先刪除一個(gè)表: user_online

mysql> drop table user_online;
Query OK, 0 rows affected (0.01 sec)
# 1、從全備份中提取出該表的建表語句[root@pre ~]# sed -e'/./{H;$!d;}' -e 'x;/CREATE TABLE `user_online`/!d;q' all_database_bak_471_2017-12-04_15_36_38.sql > user_online.sql &# 2、提取該表的insert into語句[root@pre ~]# grep -i 'INSERT INTO `user_online`' all_database_bak_471_2017-12-04_15_36_38.sql >> user_online.sql & # 3、導(dǎo)入到對(duì)應(yīng)的庫中[root@pre ~]# /home/mysql/mysql55_3310/bin/mysql -uroot -p <user_online.sql & # 4、查看數(shù)據(jù)
mysql> select count(*) from user_online;+----------+| count(*) |+----------+| 9 |+----------+1 row in set (0.01 sec)
# 已經(jīng)恢復(fù)完畢