[MySQL]mysql binlog回滚数据
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