用mysqlbinlog做基於時間點的資料恢復一例

chenfeng發表於2017-01-25
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+
4 rows in set (0.00 sec)


mysql> use test
Database changed
mysql> show tables;
Empty set (0.00 sec)


mysql> show binary logs;
+------------------+-----------+
| Log_name         | File_size |
+------------------+-----------+
| mysql-bin.000001 |       120 |
+------------------+-----------+
1 row in set (0.00 sec)


mysql>
mysql>
mysql> flush logs;
Query OK, 0 rows affected (0.16 sec)


mysql> show binary logs;
+------------------+-----------+
| Log_name         | File_size |
+------------------+-----------+
| mysql-bin.000001 |       167 |
| mysql-bin.000002 |       120 |
+------------------+-----------+
2 rows in set (0.00 sec)

建立一個新表chenfeng並插入三條記錄:
mysql> create table chenfeng(t1 int not null primary key,t2 varchar(50),t3 datetime);
Query OK, 0 rows affected (0.13 sec)


mysql> insert into chenfeng values (1,"beijing",now());
Query OK, 1 row affected (0.02 sec)


mysql> insert into chenfeng values (2,"shanghai",now());
Query OK, 1 row affected (0.02 sec)


mysql> insert into chenfeng values (3,"zhengzhou",now());
Query OK, 1 row affected (0.03 sec)


mysql> select * from chenfeng;
+----+-----------+---------------------+
| t1 | t2        | t3                  |
+----+-----------+---------------------+
|  1 | beijing   | 2017-01-25 15:33:54 |
|  2 | shanghai  | 2017-01-25 15:34:08 |
|  3 | zhengzhou | 2017-01-25 15:34:23 |
+----+-----------+---------------------+
3 rows in set (0.00 sec)


現在我們執行delete誤操作,刪除所有的資料:
mysql> delete from chenfeng;
Query OK, 3 rows affected (0.04 sec)


先檢視binlog,生成002.sql:
mysqlbinlog mysql-bin.000002 > 002.sql

檢視002.sql,並只摘取delete部分內容:
BEGIN
/*!*/;
# at 1094
#170125 15:37:10 server id 1  end_log_pos 1188 CRC32 0x53d8348f         Query   thread_id=197   exec_time=0     error_code=0
SET TIMESTAMP=1485329830/*!*/;
delete from chenfeng
/*!*/;
# at 1188
#170125 15:37:10 server id 1  end_log_pos 1219 CRC32 0xfe067937         Xid = 25
COMMIT/*!*/;
DELIMITER ;
# End of log file
ROLLBACK /* added by mysqlbinlog */;
/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;
/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;


可以看到在時間2017-01-25 15:37:10我們做了delete誤操作。現在需要用mysqlbinlog恢復到這個時間點前的資料:
# mysqlbinlog mysql-bin.000002 --stop-date='2017-01-25 15:37:10' > resume.sql

執行resume.sql內容後發現資料已恢復:
mysql> select * from chenfeng;
+----+-----------+---------------------+
| t1 | t2        | t3                  |
+----+-----------+---------------------+
|  1 | beijing   | 2017-01-25 15:33:54 |
|  2 | shanghai  | 2017-01-25 15:34:08 |
|  3 | zhengzhou | 2017-01-25 15:34:23 |
+----+-----------+---------------------+
3 rows in set (0.00 sec)

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/15498/viewspace-2132912/,如需轉載,請註明出處,否則將追究法律責任。

相關文章