Most of the time, you can easily manage your database with web-based tools such as phpMyAdmin. Unfortunately there are times when you need to restore a large amount of data which can’t be done through phpMyAdmin because if PHP’s limits (either the maximum time a PHP script can use or the maximum file size upload).
Whether you are using MySQL on Linux or MS Windows, you can use the command line to perform most tasks. If you are using MS Windows, make the path to the command line binaries is included in your system path. This will make things easier for you otherwise you’ll have to type the full path to each command.
MySQL provides a utility called “mysqldump”. Basically what this tool does it it creates a flat file containing the SQL instructions to restore your database. Here are a few usage examples of mysqldump:
Creating a simple database backup
mysqldump -u username -p database_name > file.sql
This will create a file containing all the SQL statements to create tables and restore data into an existing database. If the target database contains tables with the same names, they will be overwritten. If you want the existing tables to be dropped and recreated, use the add-drop-table option:
mysqldump –add-drop-table -u username -p database_name > file.sql
You could also choose to drop the whole database before recreating it and restoring data:
mysqldump –add-drop-databases -u username -p database_name > file.sql
Backing Up Multiple Databases
You can backup multiple databases to a single file using the databases option:
mysqldump -u username -p –databases database1 database2 database3 > file.sql
Creating a backup of all databases can be achieved using the all-databases option:
mysqldump -u username -p –all-databases > file.sql
Backing Up InnoDB Tables
If you database has InnoDB tables, you will need to deactivate referential integrity while restoring data. Unfortunately, this can’t be done using the mysqldump utility. To do so, backup your database as you would normally. When done, open the SQL file and add the following statement at the very beginning:
…and add the following at the end of the file:
If you are using mysqldump in a Linux shell, you can pipe it through gzip to compress the dump file (assuming you have gzip installed):
mysqldump -u username -p database_name | gzip -c file.sql.gz
To restore a backup created with mysqldump, you will need to use the mysql command. If your SQL dump file does not contain any “create database” statement, you can use the following command:
mysql -u username -p database_name < file.sql
But if it does, simply use the same command without specifying the database name:
mysql -u username -p < file.sql
More information on mysqldump can be found here.