Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to get this CSV file that I exported from excel loaded into my database and I can't seem to get the formatting correct no matter what I try.

Here is the SQL:

LOAD DATA INFILE 'path/file.csv'
INTO TABLE tbl_name 
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"' 
LINES TERMINATED BY '
' 
(column1, column2, column3); 

This works fine but then I run into trouble when the end of a line (column 3) ends in a quote. For example:

Actual value: These are "quotes"

Value in CSV: "These are ""quotes"""

What happens is that I will get an extra quote on that value in the database and also any additional lines until it reaches another quote in the CSV. Any ideas on how to solve this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
804 views
Welcome To Ask or Share your Answers For Others

1 Answer

Hmm. I tried to duplicate this problem but can't. Where does my data differ from yours? Can you provide sample data to duplicate this? Here's what I did:

> cat /tmp/data.csv
"aaaa","bbb ""ccc"" ddd",xxx
xxx,yyy,"zzz ""ooo"""
foo,bar,baz

mysql> CREATE TABLE t2 (a varchar(20), b varchar(20), c varchar(20));
Query OK, 0 rows affected (0.01 sec)

mysql> LOAD DATA INFILE '/tmp/data.csv' INTO TABLE t2 FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '
' (a, b, c);
Query OK, 3 rows affected (0.00 sec)
Records: 3  Deleted: 0  Skipped: 0  Warnings: 0

mysql> select * from t2;
+------+---------------+-----------+
| a    | b             | c         |
+------+---------------+-----------+
| aaaa | bbb "ccc" ddd | xxx       |
| xxx  | yyy           | zzz "ooo" |
| foo  | bar           | baz       |
+------+---------------+-----------+
3 rows in set (0.00 sec)

Looks ok to me(?)

Also note that if you're working on a Windows platform you might need to use
LINES TERMINATED BY ' ' instead.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...