教你MySQL数据库误删回滚的解决方法

某次一不小心,用了delete from 删除了几条重要数据,在网上找了很多方法,但都比较零散,打算记录本次数据找回的过程。
大致分为以下几步

1、查看binlog是否开启

# log_bin是ON,就说明打开了 OFF就是关闭状态,以下操作,只有为 ON 时有效。
show variables like ‘log_bin’;

2、找到binlog文件名

show master logs;

运行以上代码,如下图 TS1-bin.000009 就是我们要找的文件名

3、查看binlog日志位置

show variables like ‘%datadir%’;

4、根据上面得到的位置,去找到 TS1-bin.000009 文件

5、进入到mysql安装目录的bin目录下,执行以下命令根据误删除的时间范围从TS1-bin.000009文件导出成sql文件

mysqlbinlog –base64-output=decode-rows -v –database=数据库名 –start-datetime=”2022-06-29 15:35:00″ –stop-datetime=”2022-06-29 15:45:00″ C:/Users/Administrator/Desktop/TS1-bin.000009 > C:/Users/Administrator/Desktop/mysqllog.sql

这里我把 TS1-bin.000009 文件拷贝到了桌面,因为该文件原始存放路径有空格,导致命令执行失败,无法找到路径。
得到 mysqllog.sql 文件后,可以用记事本打开,搜索 DELETE 关键字,找到删除数据的记录

6、将 DELETE 语句改造成 INSERT 语句,在windows下用vbs来实现,把下面代码复制保存为:deleteToinsert.vbs 文件(一定要是.vbs格式文件) 与mysqllog.sql在同一目录下,然后双击运行,会生成mysqllogOK.sql文件就是我们要的INSERT语句

‘========================== 
‘用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

7、拿到对应的 INSERT 语句后执行。

参考文章

https://blog.csdn.net/qq_36602951/article/details/120729047
https://juejin.cn/post/7028955574242902023

到此这篇关于MySQL数据库误删回滚的解决的文章就介绍到这了,更多相关MySQL数据库误删回滚内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


数据运维技术 » 教你MySQL数据库误删回滚的解决方法