Restore an Entire Database
Now that you have backups, let's practice restoring them. In this step, you will simulate a disaster by deleting the entire mydatabase and then restoring it from your full backup file.
First, let's drop the database. The -e flag allows you to execute a single SQL command directly from your terminal.
sudo mysql -u root -e "DROP DATABASE mydatabase;"
Verify that the database is gone.
sudo mysql -u root -e "SHOW DATABASES;"
You will see that mydatabase is no longer in the list.
Before you can restore the data, you must create an empty database with the same name.
sudo mysql -u root -e "CREATE DATABASE mydatabase;"
Now, restore the database by redirecting the mydatabase_backup.sql file as input to the mysql client.
sudo mysql -u root mydatabase < /home/labex/backup/mydatabase_backup.sql
The command will execute all the SQL statements in the backup file, recreating the tables and inserting the data.
To verify the restoration, connect to MySQL and check the tables and their content.
sudo mysql -u root
At the mysql> prompt, run these commands:
USE mydatabase;
SHOW TABLES;
SELECT * FROM users;
You should see the products and users tables again, and the users table should contain its original data.
+--------------------+
| Tables_in_mydatabase |
+--------------------+
| products |
| users |
+--------------------+
2 rows in set (0.00 sec)
+----+------------+--------------------------+
| id | name | email |
+----+------------+--------------------------+
| 1 | John Doe | john.doe@example.com |
| 2 | Jane Smith | jane.smith@example.com |
+----+------------+--------------------------+
2 rows in set (0.00 sec)
Exit the MySQL shell.
exit
You have successfully recovered the entire database from a catastrophic failure.