系统环境
bash
#系统版本
# cat /etc/redhat-release
CentOS Linux release 7.9.2009 (Core)
#数据库版本
# mysql -V
mysql Ver 14.14 Distrib 5.7.44, for Linux (x86_64) using EditLine wrapper
恢复前提
本文仅适合mysql数据库已经开启binlog日志的情况。
查看binlog是否开启
bash
mysql> show variables like '%log_bin%';
+---------------------------------+--------------------------------+
| Variable_name | Value |
+---------------------------------+--------------------------------+
| log_bin | ON |
| log_bin_basename | /var/lib/mysql/mysql-bin |
| log_bin_index | /var/lib/mysql/mysql-bin.index |
| log_bin_trust_function_creators | OFF |
| log_bin_use_v1_row_events | OFF |
| sql_log_bin | ON |
+---------------------------------+--------------------------------+
# ON 表示成功开启
查看binlog路径
bash
mysql> show variables like '%datadir%';
+---------------+-----------------+
| Variable_name | Value |
+---------------+-----------------+
| datadir | /var/lib/mysql/ |
+---------------+-----------------+
1 row in set (0.00 sec)
恢复操作
模拟删除数据
bash
mysql> delete from task_fail where id = 20;
Query OK, 1 row affected (0.38 sec)
mysql> delete from task_fail where id = 21;
Query OK, 1 row affected (0.04 sec)
mysql> delete from task_fail where id = 22;
Query OK, 1 row affected (0.06 sec)
mysql> delete from task_fail where id = 23;
Query OK, 1 row affected (0.07 sec)
mysql> select id from task_fail order by id asc;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
| 11 |
| 12 |
| 13 |
| 14 |
| 15 |
| 16 |
| 17 |
| 18 |
| 19 |
| 24 |
| 25 |
| 26 |
将删除时间段binlog翻译为sql
bash
# mysqlbinlog --base64-output=decode-rows -v --database=airflow --start-datetime="2024-05-07 15:30:00" --stop-datetime="2024-05-07 15:50:00" "/var/lib/mysql/mysql-bin.000001" > delete.sql
将上述的sql文件delete修改为insert的sql
bash
# cat delete.sql | sed -n '/###/p' | sed 's/### //g;s/\/\*.*/,/g;s/DELETE FROM/;INSERT INTO/g;s/WHERE/SELECT/g;' |sed -r 's/(@17.*),/\1;/g' | sed 's/@1=//g'| sed 's/@[1-9]=/,/g' | sed 's/@[1-9][0-9]=/,/g' > insert.sql
执行insert sql,恢复误删除数据
bash
mysql> source /root/insert.sql
ERROR:
No query specified
Query OK, 1 row affected (0.04 sec)
Records: 1 Duplicates: 0 Warnings: 0
Query OK, 1 row affected (0.03 sec)
Records: 1 Duplicates: 0 Warnings: 0
Query OK, 1 row affected (0.03 sec)
Records: 1 Duplicates: 0 Warnings: 0
Query OK, 1 row affected (0.04 sec)
Records: 1 Duplicates: 0 Warnings: 0
验收数据恢复情况
bash
mysql> select id from task_fail order by id asc;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
| 11 |
| 12 |
| 13 |
| 14 |
| 15 |
| 16 |
| 17 |
| 18 |
| 19 |
| 20 |
| 21 |
| 22 |
| 23 |
| 24 |
| 25 |
id 20 21 22 23 的数据已经恢复。