A simple way to back up MySQL databases is with the
mysqldump
command line tool. Mysqldump can be used to back up a single database or multiple databases, and can backup MySQL databases into a text file containing multiple SQL statements, or into CSV or tab delimited text files.
The simplest way to use mysqldump is like so, substituting [username] for the username you use to connect to MySQL, and [database] for the MySQL database you wish to backup:
The above example will output the dump to a file called [database].sql, but you can instead dump the data to standard output (ie a scrolling list on the command line) by omitting the
> [database].sql
part.
You will be prompted for the password (that's what the
-p
flag is for), and an example dump with a database containing a couple of basic tables with a couple of rows of data each might look like this:Dumping a single table, or a selection of tables
If you wanted to back up a single table or a selection of tables from the database, you can specify these on the command line after the database name as shown in the following examples. The first example below would dump the table "foo", the second "foo" and "bar", and the third "foo", "bar" and "baz".
Loading the data from the file
Now that you've successfully dumped the data from the database into a text file, how do you get it back into the database again? It's really easy, again doing it from the command line. By default, the mysqldump command adds
"DROP TABLE IF EXISTS `tablename`"
to the query, so you can simply run the contents of the file against the database and it will delete the table if it exists, and then load the data into the database.
This can be useful for a) backing up databases on a regular basis and b) when copying the contents of the database or table(s) from a remote server to your local development machine.
There are a lot of additional flags for dumping data from MySQL using mysqldump. I will explore some of these in later posts and there's also an excellent man page (
man mysqldump
) and running mysqldump --help
will list the many options available.
0 comments:
Post a Comment