2.6. Backing up and restoring MySQL data with logical dumps
A logical backup of MySQL data consists of the SQL statements necessary to restore the data. The advantage of logical backup over physical backup is that the data can be restored on other hardware configurations and MySQL versions.
2.6.1. Performing a logical backup by using mysqldump 复制链接链接已复制到粘贴板!
The mysqldump utility is a backup utility that can export one or more databases. The output of mysqldump typically consists of SQL statements to re-create the server table structure, populate it with data, or both.
To perform the mysqldump backup, you can use one of the following options:
- Back up one or more selected databases
- Back up all databases
- Back up a subset of tables from one database
Procedure
To dump a single database, run:
# mysqldump [options] --databases db_name > backup-file.sqlTo dump multiple databases at once, run:
# mysqldump [options] --databases db_name1 [db_name2 ...] > backup-file.sqlTo dump all databases, run:
# mysqldump [options] --all-databases > backup-file.sqlTo load one or more dumped full databases back into a server, run:
# mysql < backup-file.sqlTo load a database to a remote MySQL server, run:
# mysql --host=remote_host < backup-file.sqlTo dump a subset of tables from one database, add a list of the chosen tables at the end of the
mysqldumpcommand:# mysqldump [options] db_name [tbl_name ...] > backup-file.sqlTo load a subset of tables dumped from one database, run:
# mysql db_name < backup-file.sql注意The db_name database must exist at this point.
To see a list of the options that
mysqldumpsupports, run:$ mysqldump --help
2.6.2. Restoring MySQL data from a dump in SQL format 复制链接链接已复制到粘贴板!
If you backed up one or multiple databases to an SQL file, you can use this file to re-create the database structure and its data.
Prerequisites
-
The
mysqldservice is running. -
You have credentials with permissions to restore data, for example, the
rootaccount.
Procedure
If the database you want to restore already exists and your SQL file does not contain
DROP TABLE IF EXISTSstatements, you must manually remove the tables or the entire database:To remove a table, enter:
# mysql -u root -p -e "DROP TABLE <database>.<table>;"Repeat this command for every table that the SQL file will re-create.
To remove a database, enter:
# mysql -u root -p -e "DROP DATABASE <database>;"Repeat this command for every database that the SQL file will re-create.
Import the SQL file:
# mysql -u root -p < backup.sql"
Verification
Connect to a MySQL database and query data, for example:
# mysql -u root -p <database> -e "*SELECT * FROM <table>;"