Recipe 10.14. Exporting Tables as Text Files


Problem

You want to export an entire table to a file.

Solution

Use the mysqldump program with the --tab option.

Discussion

The mysqldump program is used to copy or back up tables and databases. It can write table output either as a text datafile or as a set of INSERT statements that recreate the rows in the table. The former capability is described here, the latter in Recipes Section 10.15 and Section 10.16.

To dump a table as a datafile, you must specify a --tab option that indicates the directory on the MySQL server host to which you want the server to write the file. (The directory must already exist; the server won't create it.) For example, to dump the states table from the cookbook database to a file in the /tmp directory, use a command like this:

% mysqldump --no-create-info --tab=/tmp cookbook states             

mysqldump creates a datafile using the table name plus a .txt suffix, so this command writes a file named /tmp/states.txt. This form of mysqldump is in some respects the command-line equivalent of SELECT ... INTO OUTFILE. For example, it writes out a table as a datafile on the server host, and you must have the FILE privilege to use it. See Section 10.13 for a list of general properties of SELECT ... INTO OUTFILE.

If you omit the --no-create-info option, mysqldump also creates a file /tmp/states.sql on your local host that contains the CREATE TABLE statement for the table. (The latter file will be owned by you, unlike the datafile, which is owned by the server.)

You can name multiple tables after the database name, in which case mysqldump writes output files for each of them. If you don't name any tables, mysqldump writes output for every table in the database.

mysqldump creates datafiles in tab-delimited, linefeed-terminated format by default. To control the output format, use the --fields-enclosed-by, --fields-terminated-by, and --lines-terminated-by options (that is, the same options that mysqlimport understands as format specifiers). For example, to write the states table in CSV format with CRLF line endings, use this command:

% mysqldump --no-create-info --tab=/tmp \                --fields-enclosed-by="\"" --fields-terminated-by="," \                --lines-terminated-by="\r\n" cookbook states             

A datafile exported this way can be imported using LOAD DATA or mysqlimport. Be sure to use matching format specifiers when importing if you didn't dump the table using the default format.




MySQL Cookbook
MySQL Cookbook
ISBN: 059652708X
EAN: 2147483647
Year: 2004
Pages: 375
Authors: Paul DuBois

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net