1. Related variables view
- Whether to open binlog
show variables like 'log_bin';
- Three modes of binlog
show variables like '%binlog_format%';
Two, placement
- Configure my.conf
[mysqld] server-id = 1 log-bin = /var/log/mysql/mysql-bin.log #设置log-bin文件自动会开启binlog binlog_format = ROW #格式 expire-logs-days = 14 #14天内 max-binlog-size = 500M #每个binlog文件最大值
- Restart mysql
- mysql-bin.000001 log file and mysql-bin.index index file under the /var/log/mysql/ folder, binlog is a binary file
Three, log SQL operations
- View the log file list
show master logs;
- Generate a new log file
flush logs;
- Clear log file
reset master;
3. Data testing and backup
The backup is not real-time, there will be many states in the recovery of data errors
- Latest backup status
- After backup to before error operation
- User normal operation after wrong operation
We need to restore the backup first and then retrieve it through binlog and skip the wrong operation
create database test_binlog;
use test_binlog;
create table t1 (
id int unsigned not null auto_increment primary key,
uname varchar(10) not null default ''
);
insert into t1(uname) values('a');
flush logs;
insert into t1(uname) values('b');
flush logs;
insert into t1(uname) values('c');
flush logs;
# 此时binlog最新为mysql-bin.000004
# 备份数据库 test_binlog, 模拟定时备份
mysqldump -uroot -p test_binlog > /tmp/backup.sql
# 备份后的数据修改
insert into t1(uname) values('d');
# 啊呀!没带条件把所有数据都改了,这是错误的!
update t1 set uname = '哈哈哈';
# 用户正常操作-删除
delete from t1 where id = 2;
# 用户正常操作-发现数据怎么不读,我自己改回去吧
update t1 set uname = 'c' where id = 3;
Five, backup and recovery
1. 系统停止服务 show master status; 得到最新日志 mysql-bin.000004 , position=3099
2. 保护车祸现场,flush logs; 生成新的日志文件 mysql-bin.000005 , 防止 mysql-bin.000004 被修改
3. 登录SQL,use test_binlog;
4. 恢复备份 source /tmp/backup.sql;
5. 我们测试只有最开始的小a。 如果是正常的话应该是大部分数据都回来了,好开心
6. 接下来就需要通过binlog恢复备份之后的数据了
Three, binlog recovery
- Check the log
show binlog events in 'mysql-bin.000004' ;
to find the rollback statement
found so easy to find, SQL is not exposed - Extract and translate binlog
mysqlbinlog --no-defaults --base64-output=decode-rows -v --start-datetime='2021-01-05 15:00:00' --stop-datetime='2021-01-05 15:25:00' /var/log/mysql/mysql-bin.000004 > /tmp/binlog.sql
-v
execution
--start-datetime
interception start time and
--stop-datetime
interception end time - View
/tmp/binlog.sql
can see the insert commit d of the position = 570, the next step is to update ha ha ha.
We recover data in accordance with pointmysqlbinlog -v --stop-position=570 /var/log/mysql/mysql-bin.000004 | mysql -u root -p
at this time, we have restored the state is off state before execution of SQL errors, also need to perform SQL error after SQL
executionmysqlbinlog -v --start-position=924 /var/log/mysql/mysql-bin.000004 | mysql -u root -p
so far, we have returned to relatively correct data. Because do you want to consider why the user deletes the second article? And so on.