在mysql中我们平常使用的是mysqldump来备份数据库文件,假如我们是一天一备份,在今天凌晨备份完一份,但是当我们在这天的上午某个时间数据库突然崩溃了,数据全部丢失了,我们该怎么办
当然我们可以把凌晨备份的数据还原,但是还有这半天的数据在哪里呢,这样数据就丢失了,对于这种情况,我们可以使用mysql的bin-log开处理
首先我们要先打开mysql的bin-log日志功能,可以在/etc/my.cnf中修改
查看一下mysql的bin-log日志状态
mysql> show master status;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 | 106 | | |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)
这里我们可以看到一个position属性,这个是用来记录mysql增删改等操作时记录下来的位置
比如我们建一张表,在插入几行数据,再来查看
mysql> create table t1(id int);
Query OK, 0 rows affected (0.14 sec)
mysql> insert into t1 values(1),(2);
Query OK, 2 rows affected (0.06 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> show master status;
+------------------+----------+--------------+------------------+
| File | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 | 283 | | |
+------------------+----------+--------------+------------------+
1 row in set (0.00 sec)
可以看到position的位置发生了变化,再看一个mysql-bin.000001中的数据
可以看到我们刚刚的操作
现在我们来看一下数据备份的操作,可以来模拟一下
首先,我们需要备份下今天以前的数据
我们采用mysqldump来操作
我们可以看到在/tmp下有一个test.sql文件
上面的操作, -F就是flush logs 用来刷新日志,生成一个新的bin-log日志文件,-l就是把数据库读锁,不允许插入,删除等操作
现在我们的数据库内容是
mysql> select * from t1;
+------+
| id |
+------+
| 1 |
| 2 |
+------+
2 rows in set (0.00 sec)
我们进行一下操作
mysql> insert into t1 values (3),(4);
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
mysql> select * from t1;
+------+
| id |
+------+
| 1 |
| 2 |
| 3 |
| 4 |
+------+
4 rows in set (0.00 sec)
在这时,突然数据库崩溃,数据全部丢失
首先,先把test.sql恢复
[root@localhost tmp]# mysql -uroot -proot test </tmp/test.sql
可以看到现在数据库里是
mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| songs |
| t1 |
| tt |
+----------------+
3 rows in set (0.00 sec)
mysql> select * from t1;
+------+
| id |
+------+
| 1 |
| 2 |
+------+
2 rows in set (0.00 sec)
恢复到了这个程度,接下来就要使用bin-log日志来恢复了
再来查看一下数据库里的内容
mysql> select * from t1;
+------+
| id |
+------+
| 1 |
| 2 |
| 3 |
| 4 |
+------+
4 rows in set (0.00 sec)
这样就恢复完成了
这里我们用到了 mysqlbinlog --no-defaults mysql-bin.000002|mysql -uroot -proot test命令
mysqlbinlog可以用来对mysql的binlog日志进行查看和恢复
当然,我们也可以根据position和时间来进行恢复操作
mysqlbinlog --no-defaults --start-position=192 --stop-position=328 mysql-bin.000002|mysql -uroot -proot test
也可以是时间
--start-date="2013-11-26 11:00:00"
--stop-date="2013-11-27 11:00:00"
只是时间没有position来的精确
至此,我们恢复数据是可以使用mysqldump+binlog来操作