mysql如何從全備文件中恢復單個庫或者單個表


mysql如何從全備文件中恢復單個庫或者單個表

  在mysql dba的日常實際工作中,一個實例下有多個庫,而我們常見的備份就是全庫備份。那么問題就來了,如果需要恢復單個庫或者單個表,怎么辦了,網上有很多人都有多種方法,今天,我自己結合眾多資料,將實踐記錄下來,以便供參考。
基本情況介紹:
mysql版本:mysql-5.5.36.tar.gz
操作系統: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=3310
user=root
password=123456
socket=/home/mysql/mysql55_3310/data/mysql.sock
[root@pre ~]# sh backup.sh
View Code

二、顯示當前庫

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)
View Code

三、現在從全備文件中恢復db_log單個庫

# 從全備份文件中將需要的庫的建表語句和INSERT數據拿出來,然后再導入
[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 &
# 導入庫中
[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 -A

Database 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> 

#  數據已經恢復了
View Code

四、現在模擬恢復單個表的數據

# 先刪除一個表: 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、導入到對應的庫中
[root@pre ~]# /home/mysql/mysql55_3310/bin/mysql -uroot -p <user_online.sql & 

# 4、查看數據
mysql> select count(*) from user_online;
+----------+
| count(*) |
+----------+
|        9 |
+----------+
1 row in set (0.01 sec)

# 已經恢復完畢
View Code

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM