Thursday, November 8, 2007

Importing From CSV Into MySQL

For importing data into a MySQL database from a CSV (comma-separated values) file, the MySQL documentation is good but a little imprecise.

This is useful for extracting data from an Excel spreadsheet and adding to a database. Note that an Excel spreadsheet can be "Saved-As" a CSV file.

Given a CSV file consisting of 5 columns of data, first create a table with the 5 columns appropriate for the data then use the LOAD DATA command from the mysql prompt.

mysql> create table emailimport (EmailAddress VARCHAR(100), RegDate VARCHAR(9), Flag CHAR(1), CustID CHAR(8), DivID CHAR(3));

mysql> LOAD DATA INFILE "C:\\DOCUME~1\\GREG\\DESKTOP\\DC\\LBC1.CSV" INTO TABLE emailimport FIELDS TERMINATED BY ',';