Clue Mediator

How to Backup and Restore MySQL/MariaDB Databases using Command Line

πŸ“…August 2, 2023
πŸ—MySQL

Backing up your MySQL or MariaDB databases is essential to protect your data from accidental loss, server failures, or any unforeseen incidents. Additionally, having a reliable backup ensures you can restore your data in case of data corruption or if you need to migrate your databases to a new server. In this blog post, we'll walk you through the steps to backup and restore MySQL/MariaDB databases using the command line, providing you with the peace of mind that your valuable data is safe.

Steps to Backup and Restore MySQL/MariaDB Databases

  1. Access MySQL Command Line
  2. Backup the Database
  3. Restore the Database
  4. Backup All Databases
  5. Restore All Databases

1. Access MySQL Command Line

To begin, open your terminal and access the MySQL command line interface using the following command, replacing <username> with your MySQL username and <password> with your password:

mysql -u <username> -p

After entering your password, you'll be logged into the MySQL command line.

2. Backup the Database

To create a backup of a specific database, use the mysqldump command. For example, to backup a database named "mydatabase", use the following command:

mysqldump -u <username> -p mydatabase > mydatabase_backup.sql

This command will create a SQL file named "mydatabase_backup.sql" containing the backup of your "mydatabase".

3. Restore the Database

To restore a database from a previously created backup, first, create an empty database where you want to restore the data. You can do this using the MySQL command line:

CREATE DATABASE mydatabase;

Next, use the following command to restore the data from the backup file:

mysql -u <username> -p mydatabase < mydatabase_backup.sql

This command will restore the data from "mydatabase_backup.sql" to the "mydatabase" you created.

4. Backup All Databases

To backup all databases at once, use the following command:

mysqldump -u <username> -p --all-databases > alldatabases_backup.sql

This command will create a backup file named "alldatabases_backup.sql" containing all the databases.

5. Restore All Databases

To restore all databases from the backup file "alldatabases_backup.sql," use the following command:

mysql -u <username> -p < alldatabases_backup.sql

This command will restore all databases from the "alldatabases_backup.sql" file.

Conclusion

Backing up and restoring MySQL/MariaDB databases using the command line is a crucial skill for database administrators and developers. Regular backups provide an extra layer of security, ensuring your data remains intact and accessible in case of any unexpected events.

By following the simple steps outlined in this blog post, you can confidently create backups and restore your databases, safeguarding your valuable data and easing any worries about data loss.

Happy coding! 😊