Even with reliable software and competent users, there are still countless ways to lose or corrupt your MySQL data from your database server.Â Fortunately, recovery is actually a straightforward process when you have reliable backups.
InnoDB has an automatic internal recovery system, which much of the time operates transparently.Â In the case of database hosting failure, InnoDB attempts to fix it by running the log file from the last timestamp.Â In many cases, it succeeds—during power failure or an operating system crash, for example, InnoDB itself takes care of recovering all the data.Â Â But when InnoDB fails this automatic repair process, the entire database will not start.
It is important to schedule regular backups of your database.Â The mysqldump utility is a helpful tool to make a backup of your data as a snapshot in a point of time.Â Use this command to create a “dump file” of your MySQL database.
shell> mysqldump --single-transaction --flush-logs --master data=2 \
Â Â Â Â Â Â Â Â --all-databases > dump.sql
You can name the output file anything you want – here, it is dump.sql.Â This file consists of the data, tables, and structures of all databases backed up into a SQL text file, dump.sql.
The option “–single-transaction” in the command above is specifically for InnoDB tables; it performs an online backup that takes no locks on tables.
To make incremental backups, however, you need to save incremental changes, a process best accomplished using the binary logs.Â MySQL should always be started with the –log-bin option to enable that binary log.Â In the mysqldump command above, the “–flush-logs” option causes the server to flush its logs.Â You can flush the logs incrementally between dump backups to contain all the data changes made since that backup.
Now, suppose your database has a catastrophic crash.Â It is simple to restore when you have regular backups as well as binary logs.Â First, restore to the last full backup that you have.
shell>Â mysql < dump.sql
The data is restored to the state that it was at your last mysqldump backup.Â To restore the changes since then, use the incremental backups, from the binary log files which will be listed in the data directory of your MySQL server (here, logfilename-bin.000001 and logfilename-bin.000002).
shell> mysqlbinlog logfilename-bin.000001 logfilename-bin.000002 | mysql