Friday, May 24, 2013

sql:mysql:LOAD DATA INFILE:csv file with date field

While importing data from a csv file into a table; if the csv file contains a date field(s) that is not in the MySql format (yyyy-mm-dd), problems arise.
The following method can be used to overcome this -

Example csv file:

,Donald Grump,MV,04/30/2004,1
,Ed Burner,RD,03/15/2010,1

Command:

LOAD DATA INFILE '/usr/share/data/candidates.csv'
INTO TABLE candidates
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(candidateId, name, type, @csvDate, isActive)
SET joinDate = str_to_date(@csvDate, '%Y-%m-%d');

Explanation:
The date field in the csv file is loaded into the variable 'csvDate'.
The 'str_to_date' MySql function is used convert the date string in 'csvDate' to the MySql format (yyyy-mm-dd) and the 'joinDate' column of the candidates table set to this acceptable date, all in one stroke!

Note:
The sequence of commands is important here.
The column names of the candidates table are to be listed ONLY AFTER THE FIELD OPTIONS. The column names and the "set" options are to be at the END of the LOAD DATA INFILE command.

No comments:

Post a Comment