Tuesday, June 3, 2008

How to Import a CSV file into MySQL from Linux

Below is a step by step set of instructions on how to import a csv file into MySQL from the Linux command line. If it works correctly you will see the first 10 records displayed on screen. If your csv file has invalid characters you will get warning messages with the line number.

Create a .sql file with the following code:

truncate table table_name;

load data local infile 'csv_file.csv' into table table_name

fields terminated by ','

lines terminated by '\r\n'

ignore 1 lines

(field1, field2, etc.)

;

select * from table_name limit 10;

Then create a .sh file with the following code:

mysql -u your_username --password=your_password --show-warnings -D your_database_name <>

Run the .sh file and your csv file will be loaded into your table.

No comments: