关于MySQL表误删除数据后 依赖 binlog 恢复数据的 记录

516 阅读2分钟

关于MySQL表误删除数据后 依赖 binlog 恢复数据的 记录

背景:今天公司新业务上线,要切换支付渠道,要把之前用户存在的 提现渠道记录删除。于是,我为了方便,直接操作了线上数据库,(主库)。然后就tm删错表了。当时就G了。把用户表G了。瞬间浑身冷汗,下面说解决办法。

前提

  1. Mysql 数据库
  2. 数据库已开启 binlog 模式为 ROW

步骤

一、导出bin-log SQL

连接MySQL 导出 binlog 日志,格式为 .sql,因为原本的 binlog 打开是乱码的

mysqlbinlog 
--no-defaults 
-v 
--base64-output=decode-rows 
--start-datetime="2023-06-08 15:20:15" 
--stop-datetime="2023-06-08 15:25:00" 
--database=charge /var/lib/mysql/mysql-bin.000007 > /data/mysql/data.sql  -- bin-log 地址 > 导出SQL地址

--no-defaults :不要读任何选项文件,不加这个命令会报错

--start-position= :起始pos点,例如:--start-position=110

--stop-position= :结束pos点,例如:--stop-position=200

--start-datetime= :起始时间,例如:--start-datetime="2020-07-18 19:00:00"

--stop-datetime= :截至时间,例如:--stop-datetime="2020-07-18 21:00:00"

--database= :指定哪个库,例如:-database=binlog_test1

-v :生成带注释的sql语句(这是重点,反向还原需要看这个sql)

-v -v:生成列的的描述信息备注等

--base64-output=decode-rows :binlog部分是否显示出来的,decode-rows表示不显示binglog部分

导出后,你将得到以下类型的数据

image-20230608184027456.png

此时导出的就是 bin-log 记录的 SQL 操作,针对于删除语句,我们要进行 bin-log 逆向 使其生成 我们需要的 反向 insert 语句

二、脚本逆向SQL

复制这个脚本,后缀为.vbs 这是Windows下的,也可以去改为 linux 下

'========================== 
'用VBS实现 MYSQL binglog DELETE转INSERT 
'========================== 
function replaceregex(patern,str,tagstr) 
    dim regex,matches 
    set regex=new regExp 
    regex.pattern=patern 
    regex.IgnoreCase=true 
    regex.global=true 
    matches=regex.replace(str,tagstr) 
    replaceregex=matches 
end function
 
'======Mysql binlog DELETE转INSERT================
'VBS打开文本文件
Set oldStream = CreateObject("ADODB.Stream")
oldStream.CharSet = "utf-8"
oldStream.Open
oldStream.LoadFromFile("mysqllog.sql") 'binLog生成的DELETE原日志文件
oldText = oldStream.ReadText()
    newText=replace(oldText,"### DELETE FROM", ";INSERT INTO")
    newText=replace(newText,"### WHERE", "SELECT")
    newText=replace(newText,"###", "")
    newText=replace(newText,"@1=", "")
    newText=replaceregex("\@[1-9]=",newText, ",")
    newText=replaceregex("\@[1-9][0-9]=",newText, ",")
oldStream.Close
'VBS保存文件
Set newStream = CreateObject("ADODB.Stream")
newStream.Type = 2 'Specify stream type - we want To save text/string data.
newStream.Charset = "utf-8" 'Specify charset For the source text data.
newStream.Open 'Open the stream And write binary data To the object
newStream.WriteText newText
newStream.SaveToFile "mysqllogOK.sql", 2 'DELETE转成INSERT以后的新的SQL文件名
newStream.Close

将你导出的 SQL 文件 的名称 填写上去,双击执行。就会生成一个 逆向之后的 SQL 文件

如下:

image-20230608184514726.png

记得去除 第一行的 分号。

三、执行SQL 数据恢复

整体步骤就这些,还是希望大家用不到,这种事情发生的生产环境太可怕了。不要违规操作。后果很严重。