Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do the following MySQL csv import query terms mean?

Tags:

import

mysql

csv

For MySQL, I found the following query to import a CSV file:

LOAD DATA LOCAL INFILE '/example.csv'
INTO TABLE exampletable
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\r\n'
IGNORE 1 LINES
(example_field_name,example_field_city,example_field_state);

I'm just starting to learn, so please forgive the trivial question, but I'm wondering if someone can explain the following parts of this in a simpler way than what's in the MySQL help docs:

What does this mean?

OPTIONALLY ENCLOSED BY '"'

What does this mean?

ESCAPED BY '\\'

What do the \r and \n mean in the following?

LINES TERMINATED BY '\r\n'

Thank you for your help.

like image 568
Nathan Avatar asked Jan 18 '23 02:01

Nathan


1 Answers

Everyone thinks CSV file format is simple, it's not.... You can read it's history on wikipedia

OPTIONALLY ENCLOSED BY '"'

Some columns include the separation character. You want the following row to be loaded as 5 columns,

one, two, "three, tres, trois", four, five

ESCAPED BY '\\'

And what if your data contained a quote character?

one, two, "In France, one would say \"trois\"", four, five

LINES TERMINATED BY '\r\n'

Windows file format. Lines end with two white-space characters "carriage return" (\r) and "End of line" (\n).

Ever notice that windows notepad can't open unix files properly? That's because such files terminate lines with only the EOL character. All this dates back to the type-writer days of computing and incompatible text standards between operating systems.

like image 57
Mark O'Connor Avatar answered Jan 30 '23 04:01

Mark O'Connor