我正在尝试将从excel导出的CSV文件加载到数据库中,无论尝试如何,似乎都无法正确获得格式。
这是SQL:
LOAD DATA INFILE 'path/file.csv' INTO TABLE tbl_name FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n' (column1, column2, column3);
这可以正常工作,但是当行尾(第3列)用引号引起来时,我遇到了麻烦。例如:
实际价值: These are "quotes"
These are "quotes"
CSV值: "These are ""quotes"""
"These are ""quotes"""
发生的是,我将在数据库中的该值上获得一个额外的报价,并在该行中到达CSV中的另一个报价之前,还获得任何其他行。关于如何解决这个问题的任何想法?
嗯 我试图重复这个问题,但是不能。我的数据与您的数据有何不同?您可以提供样本数据来重复吗?这是我所做的:
> 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 '\n' (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)
对我看来还行(?)
另请注意,如果您在Windows平台上工作,则可能需要使用它 LINES TERMINATED BY '\r\n'。
LINES TERMINATED BY '\r\n'