文章目录

  • 前言
  • binlog文件相关方法
  • 步骤
  • 创建数据库、插入测试数据
  • 删除数据
  • 查看binlog是否开启
  • 查看binlog文件列表
  • 查看指定的binlog
  • 筛选出需要的数据
  • 恢复指定的数据
  • 结尾


前言

binlog文件相关方法


步骤

创建数据库、插入测试数据

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

-- ----------------------------
-- Records of t_user
-- ----------------------------
INSERT INTO `t_user` VALUES ('1', '张三');
INSERT INTO `t_user` VALUES ('2', '李四');
INSERT INTO `t_user` VALUES ('3', '王五');
INSERT INTO `t_user` VALUES ('4', '赵六');

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_数据


mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_数据库_02

删除数据

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_database_03

查看binlog是否开启

show variables like '%log_bin%';

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_mysql binlog 指定表恢复_04

查看binlog文件列表

show master logs;

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_mysql binlog 指定表恢复_05

查看指定的binlog

show binlog events in 'binlog.000053';

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_mysql_06

筛选出需要的数据

截图示例

因为我们这是测试的,所以数据较少。

通过列表数据可以看出,在Info这一列,都是set @@开始,COMMIT结束。在它们之间包含的几行表示整个操作的执行过程。

比如图中选中的绿色这一块,里面有一行Event_type的值为Delete_rows,那就表示进行了删除。

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_数据_07


现在,我们需要的是恢复数据,然后我们上面进行的操作有建库建表插入数据删除数据

我们需要的是插入数据这块,所以,我们先找到这块信息。

然后是找到开始的pos和结束的pos,分别是43125540

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_数据库_08

恢复指定的数据

mysqlbinlog binlog.000053 --skip-gtids --start-position=4312 --stop-position=5540 > test.sql

我的binlog目录

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_database_09


在binlog目录,地址栏输入cmd,然后回车。

接着输入复制进去我们编辑好的命令,然后回车:

mysqlbinlog binlog.000053 --skip-gtids --start-position=4312 --stop-position=5540 > test.sql

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_数据库_10


这时候,在本地就已经生成了这个test.sql文件

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_database_11


接着,执行这个sql

可以新打开一个cmd,然后登录mysql

mysql -uroot -proot

输入下面命令即可。

source test.sql

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_数据库_12


这里呢,因为我们只删除了两条,1和2还在,重复执行,主键冲突,所以成功回滚了两条。下次注意把多余的去掉就好了。

mysql binlog 指定表恢复 mysql binlog 按时间恢复恢复_mysql binlog 指定表恢复_13

结尾

这里只是简单备注下binlog的用法。 在测试环境用一下还可以,正式的还是要定时备份数据库比较靠谱。