Mysql之binLog数据恢复
1.确认开启binlog日志
- 查看日志是否开启命令
## ON 标识已开启
show VARIABLES like '%log_bin%'
2. 日志操作相关命令
- 查看binlog日志
## 查看binlog日志当前位置
show master status;
## 查看所有binlog日志
show master logs
- 刷新日志,产生新的日志文件
flush logs;
- 清空所有的binlog日志
reset master;
- 查看binlog日志内容命令 其中,show binlog events 查最早的binlog日志内容
### log_name 为日志名称 pos 节点位置 row_count 查看条数
show binlog events [IN 'log_name'] [FROM pos] [LIMIT row_count];
例子: 指定binlog.000002文件 从6598节点开始查起,查10条
show binlog EVENTS in 'binlog.000002' from 6598 limit 10
3. binlog日志恢复命令
- 恢复命令语法
mysqlbinlog --start-position=1256 --stop-position=1279 --database=ccsy binlog.000002 | mysql -uroot -p123456
--start-position=1256 起始pos点
--stop-position=1279 结束pos点
--start-datetime="2021-03-29 09:18:54" 起始时间点
--stop-datetime="2021-03-29 10:30:54" 结束时间点
--database=ccsy 指定只恢复ccsy数据库
- 查看binlog日志,确定怎么恢复,一般有以下几个应用场景
- 线上服务器崩溃,恢复未备份数据
- 数据库误操作,恢复到误操作之前数据
举例说明,查看日志内容
mysql>show binlog EVENTS in 'binlog.000002'
以下为日志内容:
binlog.000002 4 Format_desc 1 125 Server ver: 8.0.20, Binlog ver: 4
binlog.000002 125 Previous_gtids 1 156
binlog.000002 156 Anonymous_Gtid 1 235 SET @@SESSION.GTID_NEXT= 'ANONYMOUS'
binlog.000002 235 Query 1 319 BEGIN
binlog.000002 319 Table_map 1 429 table_id: 150 (ccsy.ccsy_notice)
binlog.000002 429 Update_rows 1 6488 table_id: 150 flags: STMT_END_F
binlog.000002 6488 Xid 1 6519 COMMIT /* xid=1347 */
binlog.000002 6519 Anonymous_Gtid 1 6598 SET @@SESSION.GTID_NEXT= 'ANONYMOUS'
binlog.000002 6598 Query 1 6682 BEGIN
binlog.000002 6682 Table_map 1 6792 table_id: 150 (ccsy.ccsy_notice)
binlog.000002 6792 Update_rows 1 12775 table_id: 150 flags: STMT_END_F
binlog.000002 12775 Xid 1 12806 COMMIT /* xid=1426 */
binlog.000002 12806 Anonymous_Gtid 1 12892 SET @@SESSION.GTID_NEXT= 'ANONYMOUS'
binlog.000002 12892 Query 1 12967 BEGIN
binlog.000002 12967 Table_map 1 13077 table_id: 150 (ccsy.ccsy_notice)
binlog.000002 13077 Update_rows 1 19060 table_id: 150 flags: STMT_END_F
binlog.000002 19060 Xid 1 19091 COMMIT /* xid=1459 */
其中 13077-19060 为模拟误操作,要恢复数据,则把数据还原到12806之前
mysqlbinlog --start-position=4 --stop-position=12806 --database=ccsy binlog.000002 | mysql -uroot -p123456