Home > DeveloperSection > Blogs > How to Back Up and Restore a MySQL Database

How to Back Up and Restore a MySQL Database


Database Database 
Ratings:
0 Comment(s)
 4177  View(s)
Rate this:

Back up From the Command Line (using mysqldump)

If you have shell or telnet access to your web server, you can backup your MySQL data by using the mysqldump command. This command connects to the MySQL server and creates an SQL dump file. The dump file contains the SQL statements necessary to re-create the database. Here is the proper syntax:

$ mysqldump --opt -u [username] -p[password] [databasename] > [backupfilename.sql]

  • [uname] Your database username
  • [pass] The password for your database
  • [dbname] The name of your database
  • [backupfile.sql] The filename for your database backup
  • [--opt] The mysqldump option

For example, to backup a database named ‘Articles’ with the username ‘Admin’ and with no password to a file Article_backup.sql, you should accomplish this command:

$ mysqldump -u Admin -p Articles > Article _backup.sql

This command will backup the ‘Articles’ database into a file called Article_backup.sql which will contain all the SQL statements needed to re-create the database.

With mysqldump command you can specify certain tables of your database you want to backup. For example, to back up only php_blog and asp_blog tables from the ‘Articles’ database accomplish the command below. Each table name has to be separated by space.

$ mysqldump -u Admin -p Articles php_blog asp_blog > Article_backup.sql

Sometimes it is necessary to back up more that one database at once. In this case you can use the --database option followed by the list of databases you would like to backup. Each database name has to be separated by space.

$ mysqldump -u Admin -p --databases Articles Articles Comments > content_backup.sql

If you want to back up all the databases in the server at one time you should use the --all-databases option. It tells MySQL to dump all the databases it has in storage.

$ mysqldump -u Admin -p --all-databases > alldb_backup.sql

The mysqldump command has also some other useful options:

--add-drop-table: Tells MySQL to add a DROP TABLE statement before each CREATE TABLE in the dump.

--no-data: Dumps only the database structure, not the contents.

--add-locks: Adds the LOCK TABLES and UNLOCK TABLES statements you can see in the dump file.

The mysqldump command has advantages and disadvantages. The advantages of using mysqldump are that it is simple to use and it take care of table locking issues for you. The disadvantage is that the command locks tables. If the size of your tables is very big mysqldump can lock out users for a long period of time.

 


Don't want to miss updates? Please click the below button!

Follow MindStick