Back Up a Single Table
In this step, you will learn how to back up a single table from a MySQL database using the mysqldump
command. This is useful when you only need to back up a specific table and not the entire database.
We will continue using the mydatabase
database and the users
table that we created in the previous step.
To back up a single table, you use the same mysqldump
command, but you specify the table name after the database name:
mysqldump -u [username] -p[password] [database_name] [table_name] > [output_file.sql]
Replace [username]
with your MySQL username (usually root
), [password]
with your MySQL password (if any), [database_name]
with the name of the database (mydatabase
), [table_name]
with the name of the table you want to export (users
), and [output_file.sql]
with the name of the file where you want to save the backup (e.g., users_backup.sql
).
In our case, the command would be:
mysqldump -u root -p mydatabase users > ~/project/users_backup.sql
You will be prompted for the MySQL root password. Enter the password (if any).
This command will create a file named users_backup.sql
in your ~/project
directory, which contains the SQL statements needed to recreate the users
table and its contents.
You can verify that the file has been created by listing the contents of your ~/project
directory:
ls ~/project
You should see both mydatabase_backup.sql
(from the previous step) and users_backup.sql
in the output.
You can also view the contents of the backup file using nano
:
nano ~/project/users_backup.sql
This will show you the SQL statements that mysqldump
generated specifically for the users
table. Press Ctrl+X
to exit nano
.
Now, let's add another table to our database to further illustrate the single table backup process. Connect to the MySQL server:
mysql -u root -p
Switch to the mydatabase
database:
USE mydatabase;
Create a new table named products
:
CREATE TABLE products (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10, 2)
);
Insert some sample data into the products
table:
INSERT INTO products (name, price) VALUES
('Laptop', 1200.00),
('Mouse', 25.00);
Exit the MySQL shell:
exit
Now, if you only want to back up the products
table, you would use the following command:
mysqldump -u root -p mydatabase products > ~/project/products_backup.sql
This will create a file named products_backup.sql
in your ~/project
directory containing only the products
table data.