Apr 14, 2011

Export/Import CSV file directly into MySQL



Instead of writing a script to pull in information from a CSV file, you can link MYSQL directly to it and upload the information using the following SQL syntax.


Export:

SELECT * INTO OUTFILE 'c:/mysqldump.csv' FIELDS TERMINATED BY ','
 OPTIONALLY ENCLOSED BY '"' ESCAPED BY '\\' LINES TERMINATED BY '\n'
FROM cities

Import:

load data local infile 'C:\\mysqldump.csv' into table cities
fields terminated by ','
enclosed by '"'
lines terminated by '\n'
(name, country, population)


The fields here are the actual cities table fields that the data needs to sit in. The enclosed by and lines terminated by are optional and can help if you have columns enclosed with double-quotes such as Excel exports, etc.

To import an Excel file into MySQL, first export it as a CSV file. Remove the CSV headers from the generated CSV file along with empty data that Excel may have put at the end of the CSV file.
You can then import it into a MySQL table by running:

No comments:

Post a Comment