1.先開啟binlog log-bin = /var/log/mysql/mysql_bin #binlog日誌文件,以mysql_bin開頭,六個數字結尾的文件:mysql_bin.000001,並且會將文件存儲在相應的xxx/xxx路徑下,如果只配置mysql_bin的話預設在C:\Progra ...
1.先開啟binlog
log-bin = /var/log/mysql/mysql_bin #binlog日誌文件,以mysql_bin開頭,六個數字結尾的文件:mysql_bin.000001,並且會將文件存儲在相應的xxx/xxx路徑下,如果只配置mysql_bin的話預設在C:\ProgramData\MySQL\MySQL Server 5.7\Data下;
binlog_format = ROW #binlog日誌格式,預設為STATEMENT:每一條SQL語句都會被記錄;ROW:僅記錄哪條數據被修改並且修改成什麼樣子,是binlog開啟並且能恢複數據的關鍵;
expire_logs_days= 10 #binlog過期清理時間;
max_binlog_size = 100m #binlog每個日誌文件大小;
binlog_cache_size = 4m #binlog緩存大小;
max_binlog_cache_size = 512m #最大binlog緩存大小。
service mysql restart #重啟一下
2.安裝binlog2sql的python代碼
https://github.com/danfengcao/binlog2sql
apt-get install python-pip
git clone https://github.com/danfengcao/binlog2sql.git && cd binlog2sql
cd binlog2sql
pip install -r requirements.txt
3.測試在一張表裡刪除了數據和更新了數據以後,看看日誌目錄里binlog的日誌生成情況,例如:
4.進入mysql查看一下開始和結束的pos位置,第一個框是刪除,下麵的是更新,開始位置和結束位置219--498 563---881
show binlog events in 'mysql-bin.000352'
5.用binlog2sql列印出sql語句和逆向回滾的sql語句,保存並導入
python binlog2sql.py -h127.0.0.1 -P3306 -uroot -p'xxxx' --start-file mysql-bin.000352 --flashback
兩條sql就可以重新執行一下了
UPDATE `my_test`.`user` SET `UPDATETIME`='2019-04-08 10:57:06', `level`=1, `UPDATETIME1`='2019-04-08 10:57:06', `extend_id`=109999, `path`='0/1/', `id`=0 WHERE `UPDATETIME`='2020-02-10 18:11:09' AND `level`=1 AND `UPDATETIME1`='2020-02-10 18:11:09' AND `extend_id`=109999 AND `path`='0/1/' AND `id`=2 LIMIT 1; #start 498 end 797 time 2020-02-10 18:11:09
INSERT INTO `my_test`.`user`(`UPDATETIME`, `level`, `UPDATETIME1`, `extend_id`, `path`, `id`) VALUES ('2019-04-08 10:57:06', 4, '2019-04-08 10:57:06', 109999, '0/1/2/4/6/', 0); #start 4 end 422 time 2020-02-10 17:40:14
增加開始和結束位置
python binlog2sql.py -h127.0.0.1 -P3306 -uroot -p'XXX' --start-file mysql-bin.000352 --flashback --start-pos 219 --end-pos 498