您的位置:首页技术文章
文章详情页

MySQL恢复误删数据图文教程

【字号: 日期:2023-09-05 20:31:47浏览:54作者:猪猪
目录1、查看是否启用 binlog 日志2、查看所有 binlog 日志3、查看正在使用的日志4、查找日志所在文件夹5、log 日志转 sql6、delete 转 insert 恢复误删总结

MySQL 恢复误删数据,针对 window 和 Linux 均适用,只需要找到对应的 binlog 目录文件,默认就是 MySQL 安装目录下的 data 文件夹

一般误删数据,先停止所有操作,备份数据库

# 备份所有数据库mysqldump -uroot -p123456 --all-databases > /backup/mysqldump/all.db# 恢复数据mysql -uroot -p db_name < /backup/mysqldump/db_name.db1、查看是否启用 binlog 日志SHOW VARIABLES LIKE '%log_bin%'

2、查看所有 binlog 日志SHOW BINARY LOGS;

3、查看正在使用的日志SHOW MASTER STATUS;

4、查找日志所在文件夹SHOW VARIABLES LIKE '%datadir%';

5、log 日志转 sql

使用上面使用的 binlog.000056 文件,先把 该文件复制到其他地方

mysqlbinlog E:\test\result\binlog.000056 > E:\test\result\db.sql

有可能报错

添加 --no-defaults 参数可以解决,但中文会乱码(使用下面 vbs 或自定义语言实现可解决 乱码问题),一般要加上时间字段转换 sql

mysqlbinlog --no-defaults --base64-output=decode-rows -v --database=oauth --start-datetime='2023-06-01 01:44:00' --stop-datetime='2023-06-01 01:48:00' F:\mysql-8.0.29-winx64\data\binlog.000058 > E:\test\result\db.sql

转换成功如下,可以看到删除 sql 的语句

接下来只需要将上面的 delete 语句转换为 inert 即可恢复误删数据,如果需要转换的多可以通过代码自定义实现,主要就是将delete 转 insert

6、delete 转 insert 恢复误删

通过 vbs 脚本转换 sql 语句,当然也可以使用其他的语言,window 执行 vbs 不需要额外的环境,你只需要修改下面 vbs 文件中输入输出文件名以及编码类型即可

'=========================='用VBS实现 MYSQL binglog DELETE 转 INSERT'==========================function replaceregex(patern,str,tagstr)dim regex,matchesset regex=new regExpregex.pattern=paternregex.IgnoreCase=trueregex.global=truematches=regex.replace(str,tagstr)replaceregex=matchesend function'Mysql binlog DELETE转INSERT=========='VBS打开文本文件Set oldStream = CreateObject('ADODB.Stream')oldStream.CharSet = 'utf-8'oldStream.Open'binLog 生成的 DELETE 原日志文件'oldStream.LoadFromFile('E:\test\result\db.sql') 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 objectnewStream.WriteText newTextnewStream.SaveToFile 'mysqllogOK.sql', 2 'DELETE转成INSERT以后的新的SQL文件名newStream.Close

转换结果如下,自行选择新增恢复数据

总结

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

标签: MySQL 数据库