首先開啓binlog。mysql
修改mysql配置/etc/mysql/mysql.conf.d/mysqld.cnf(window環境是mysql安裝目錄的my.ini)sql
server-id = 10 //mysql服務器的惟一標示 log_bin = /var/log/mysql //存放二進制log文件的路徑
重啓mysql。數據庫
進入Mysql執行下面命令。服務器
show variables like '%log_bin%';
顯示這些信息就表示配置成功。工具
log_bin ON log_bin_basename /var/log/mysql/mysql-bin log_bin_index /var/log/mysql/mysql-bin.index log_bin_trust_function_creators OFF log_bin_use_v1_row_events OFF sql_log_bin ON
查看日誌文件測試
show master status;
mysql-bin.000001 154 日誌
mysql-bin.000001 文件是二進制文件。code
咱們能夠在終端使用Mysql的 mysqlbinlog 工具。server
查看log命令rem
mysqlbinlog /var/log/mysql/mysql-bin.000001;
導出命令
mysqlbinlog /var/log/mysql/mysql-bin.000001 > /var/log/mysql/000001.txt;
導出某段時間命令
mysqlbinlog --start-datetime='2016-11-15 00:00:00' --stop-datetime='2016-11-16 00:00:00' /var/log/mysql/mysql-bin.000001 > /var/log/mysql/000001.txt
導出某段位置命令
mysqlbinlog --start-position='50' --end-position='100' /var/log/mysql/mysql-bin.000001 > /var/log/mysql/000001.txt
其餘操做能夠查看MySQL的幫助手冊。
下面實現誤操做的數據恢復。
從新生成bin-log
flush logs;
查看日誌文件
show master status;
mysql-bin.000002 154
建立測試表
create table test(id int(11) auto_increment not null primary key, val varchar(20));
插入數據
insert into test(val) values('liang'); insert into test(val) values('jia');
誤刪除了這個表
drop table test;
而後是查看binlog文件。
show master status;
導出binlog
mysqlbinlog /var/log/mysql/mysql-bin.000002 > /var/log/mysql/000002.txt;
打開000001.txt 能夠看到位置1123執行刪除操做。
#161116 15:10:41 server id 10 end_log_pos 996 CRC32 0xe8c2dd15 Anonymous_GTID last_committed=3 sequence_number=4 SET @@SESSION.GTID_NEXT= 'ANONYMOUS'/*!*/; # at 996 #161116 15:10:41 server id 10 end_log_pos 1123 CRC32 0x8956ff72 Query thread_id=7 exec_time=0 error_code=0 SET TIMESTAMP=1479309041/*!*/; DROP TABLE `test` /* generated by server */
執行命令恢復數據。
sudo mysqlbinlog mysql-bin.000002 --stop-position=996 | mysql -uhomestead -p
輸入數據庫密碼。從新進入mysql,數據恢復了。