Mysql Load & Exporting Data

Looking for ways to export or import data from mysql?

If you are interested in importing data but you don’t want to import the structure of the data, you can export data to a csv file and then re-import the file into the database by loading the data file.

IMPORTING DATA FROM CSV FILE (MYSQL):

LOAD DATA INFILE ‘/file/location/file’ INTO TABLE tablename FIELDS TERMINATED BY ‘,’ LINES TERMINATED BY ‘\n’ (field1, field2, field3);

Fields can be terminated by tab ‘\t’ or a single quote ‘\” or a double quote ‘\”‘. Although I highly recommend that you use either commas or tabs. Using other delimiters may cause you some headaches with the right situation in the future.

If you don’t need quotes around all fields (e.g. numeric fields) then change “ENCLOSED BY” to “OPTIONALLY ENCLOSED BY” and MySQL will only put quotes around the fields that need them. Some systems require all fields in a CSV file to have quotes around them so you may need to export the data with quotes around them all depending on your requirements.

EXPORTING DATA INTO CSV FILE (MYSQL);

SELECT * INTO OUTFILE ‘/file/location/file.csv’ FIELDS TERMINATED BY ‘,’ LINES ENCLOSED BY ‘\”‘ LINES TERMINATED BY ‘\n’ FROM tablename;

If you require only specific fields to export, replace “*” with the fields. For example: SELECT field1, field2, field3 INTO OUTFILE…

If you get an error like:

#1 – Can’t create/write to file ‘/tmp/products.csv’ (Errcode: 13)

It’s possible that you don’t have the proper permissions to write to the directory or that you have a file with that name already there. You will not be able to overwrite the file if it does exists.

Dump data and table to a file

mysqldump -u user -p database table > filename
Example: mysqldump -u someuser -p database table > filename.sql

Dump the entire database

mysqldump -u user -p database > filename

Dump table structure and no data

mysqldump -u user -p -d database table > filename.sql

2 Responses

Subscribe to comments with RSS, or TrackBack to 'Mysql Load & Exporting Data'.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>