23
May 10

Text Files and MySQL databases

If for some strange reason you have to import CSV file directly into MySQL here is a good query to go:

mysql> LOAD DATA INFILE 'file.csv' INTO TABLE table_name FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\r\n' (column1, column2);

It gives you all the options such as how fields are terminated, enclosed and so on. The above example is specific for a csv file created with a Windows Text Editor. (windows... haha)

Similarly, if you have to export a query into a text file here is how this can be done:

mysql> SELECT column1, column2 INTO OUTFILE 'file.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'LINES TERMINATED BY '\r\n' FROM table_name;