MySQL: Load data into table from file

The following piece of code shows how you can load data from a comma separated values file directly into a MySQL table:

LOAD DATA LOCAL INFILE 'C:/documents/agenda.txt' IGNORE 
INTO TABLE agenda FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n'
 (@a, @b, @c, @d, @e, @f, @g)
SET first_name=TRIM(@a), last_name=TRIM(@b), address=TRIM(@c), phone1=TRIM(@d),
phone2=TRIM(@e), email=TRIM(@f), notes=TRIM(@g)

You might have to change the LINES TERMINATED BY ‘\r\n’ into ‘\r’, depending on the EOL format the file has been saved (Windows/Linux).

Leave a Reply