Backup MySQL Databases Manually With 'mysqldump'

MySQL provides us the tool required to do this: mysqldump. As the name implies, this can make a dump of one database or even to all the databases on the server. You can see all the options on its help manual or on the mysql site.

Basically this is used like:

mysqldump [OPTIONS] database [tables]
mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
mysqldump [OPTIONS] --all-databases [OPTIONS]

Based on the fact that you need to backup one database, more than one, or all the databases. All the available options are well documented, so let me show you just a simple example how to backup and restore a single database. Let’s say that the database is called ‘wordpress‘.

To backup this database and save it in a file we run:

mysqldump wordpress > wordpress.sql

I am not using any other options; just create a dump of the database.

Now let’s assume that we need to restore this backup. How do we do this? Well as simple as this:

mysql wordpress < wordpress.sql

This will run all the backup file against the existing database as a set of mysql commands (that is what the backup file really is).

Note: this will delete all the existing data in the tables of this database and replace them with the data from the saved file.

If you want to save all the databases existing on the server:

mysqldump -A > all_dbs.sql

Now, in the example from above I have assumed that you are able to connect directly to the mysql server, without the need to enter any other parameters (if you have configured properly your .my.cnf, or if the details are the default ones: localhost, root, no password - not recommended… you should have a password!). If this is not the case, add to the command line the usual mysql parameters (the ones that are needed of course):

 -h hostname -u username -p password

And the command will look like this:

mysqldump -h hostname -u username -p wordpress > wordpress.sql

This covers the basic usage of saving and restoring one mysql database with mysqldump.