Backup and restore MySQL database

This note is about how to create a backup of MySQL database with help of command line tools and then how to restore it on the server.

So, the first step is making a dump of the DB. For that task we use mysqldump command. Here’s the code:

    mysqldump -h localhost -u root mydatabase > mydatabasebackup.sql

After dumping we will have SQL file that contains SQL command to recreate a database structure and SQL commands to restore all the data.

To restore a database out of backup we should use mysql command. It should be like in the following example:

    mysql -h localhost -u root -p -D mydatabase < mydatabasebackup.sql

It will ask you for the password.

By the way, before restoring your database you should create it in case that the database doesn’t exist.

1
2
    mysql -h localhost -u root -p
    > create database mydatabase;