基本上每个跟数据库打交道的程序员(当然也可能是你同事)都会碰一个问题,MySQL误操作后如何快速回滚?比如,delete一张表,忘加限制条件,整张表没了。假如这还是线上环境核心业务数据,那这事就闹大了。误操作后,能快速回滚数据是非常重要的。
binlog2sql快速回滚
首先,确认你的MySQL server开启了binlog,设置了以下参数:
[mysqld]server-id = 1log_bin = /var/log/mysql/mysql-bin.logmax_binlog_size = 1000Mbinlog-format = row |
如果没有开启binlog,也没有预先生成回滚SQL,那真的无法快速回滚了。对存放重要业务数据的MySQL,强烈建议开启binlog。
随后,安装开源工具binlog2sql。binlog2sql是一款简单易用的binlog解析工具,其中一个功能就是生成回滚SQL。
git clone https://github.com/danfengcao/binlog2sql.gitpip install -r requirements.txt |
然后,我们就可以生成回滚SQL了。
背景:误删了test库f表整张表的数据,需要紧急回滚。
原有数据
mysql> select * from f;+-----+-----+---------------------+| uid | did | updateTime |+-----+-----+---------------------+| 1 | 18 | 2016-12-06 12:28:18 || 2 | 19 | 2016-12-06 12:55:56 || 3 | 20 | 2016-12-07 14:00:58 || 4 | 21 | 2016-12-07 14:01:00 |+-----+-----+---------------------+误操作mysql> delete from f;Query OK, 4 rows affected (0.00 sec)f表被清空mysql> select * from f;Empty set (0.00 sec) |
回滚步骤:
登录mysql,查看目前的binlog文件
mysql> show master logs;+------------------+-----------+| Log_name | File_size |+------------------+-----------+| mysql-bin.000001 | 12262268 || mysql-bin.000002 | 132776 |+------------------+-----------+ |
最新的binlog文件是mysql-bin.000002,我们再定位误操作SQL的binlog位置
$ python binlog2sql/binlog2sql.py -h127.0.0.1 -P3306 -uadmin -p'admin' -dtest -t f --start-file='mysql-bin.000002' |
输出:
DELETE FROM `test`.`f` WHERE `did`=18 AND `updateTime`='2016-12-06 12:28:18' AND `uid`=1 LIMIT 1; #start 4 end 314DELETE FROM `test`.`f` WHERE `did`=19 AND `updateTime`='2016-12-06 12:55:56' AND `uid`=2 LIMIT 1; #start 4 end 314DELETE FROM `test`.`f` WHERE `did`=20 AND `updateTime`='2016-12-07 14:00:58' AND `uid`=3 LIMIT 1; #start 4 end 314DELETE FROM `test`.`f` WHERE `did`=21 AND `updateTime`='2016-12-07 14:01:00' AND `uid`=4 LIMIT 1; #start 4 end 314 |
生成回滚sql,并检查回滚sql是否正确
$ python binlog2sql/binlog2sql.py -h127.0.0.1 -P3306 -uadmin -p'admin' -dtest -t f --start-file='mysql-bin.000002' --start-pos=4 --end-pos=314 -B |
输出:
INSERT INTO `test`.`f`(`did`, `updateTime`, `uid`) VALUES (21, '2016-12-07 14:01:00', 4); #start 4 end 314INSERT INTO `test`.`f`(`did`, `updateTime`, `uid`) VALUES (20, '2016-12-07 14:00:58', 3); #start 4 end 314INSERT INTO `test`.`f`(`did`, `updateTime`, `uid`) VALUES (19, '2016-12-06 12:55:56', 2); #start 4 end 314INSERT INTO `test`.`f`(`did`, `updateTime`, `uid`) VALUES (18, '2016-12-06 12:28:18', 1); #start 4 end 314 |