Restore a Database using the MySQL SOURCE command
MySQL provides the SOURCE command to help you restore a database from a dump file.
To restore a database from a sql file created by the mysqldump tool, you can use MySQL SOURCE command or the mysql tool.
The procedure for backing up and restoring the Sakila sample database is demonstrated below.
Back up sakila database
To back up the sakila database, please use an administrator user or a user with privileges. Execute the following statement to make a backup for sakila database:
mysqldump --user=root --password --databases sakila --result-file=/bak/sakila.sql
The client prompts for the password. Avoid putting the password value in the command line; MySQL documents that method as insecure in its password security guidance.
After running successfully, the file /bak/sakila.sql will be generated.
Log in to the MySQL server as root user and drop the sakila database using the statement below.
DROP DATABASE sakila;
Restore the sakila database using SOURCE command
Here are the steps to restore the sakila database using the SOURCE command:
-
Connect to the MySQL server using the mysql client tool:
mysql -u root -pEnter the password for the
rootaccount and pressEnter:Enter password: ******** -
Run the following
SOURCEcommand to restore the sakila database:SOURCE /bak/sakila.sqlThis step may take several seconds.
-
Use the
SHOW DATABASESstatement to show the database list to check if the database has been restored:SHOW DATABASES LIKE 'sakila';+-------------------+ | Database (sakila) | +-------------------+ | sakila | +-------------------+Now, the sakila database has been restored.
-
Use
SHOW TABLESto check that the standard Sakilaactortable was restored; the full table list can differ if the dump contains additional objects:SHOW TABLES FROM sakila LIKE 'actor';+--------------------------+ | Tables_in_sakila (actor) | +--------------------------+ | actor | +--------------------------+The output confirms that the
actortable is present. If you need to verify every object, compare the fullSHOW TABLES FROM sakila;output with the contents of the dump.
Restore the Sakila database using mysql command
The SOURCE command needs to be logged in to run, but you can also restore he Sakila database using the mysql tool. Please use the following mysql command to restore the sakila database:
mysql --user=root --password < /bak/sakila.sql
The client prompts for the password before reading the dump file.
After excecution, you can use SHOW DATABASES and SHOW TABLES to check that the database has been recovered.
Conclusion
In MySQL, the SOURCE command can help you restore databases from backup files. In addition to that, you can restore a database using the mysql command.