MySQL从最后一列csv NULL加载infile

时间:2014-09-15 21:50:02

标签: mysql csv file-io load

我有一个包含5列数据的.csv文件。有时,最后一列包含NULL值,如此。

2014-07-11 23:55:00,1,245,0.05,0.01,0.0003
2014-07-11 23:57:00,1,245,0.05,0.01,\N
2014-01-17 20:14:00,2,215,0.05,0.009,0.002

我试图将其加载到本地数据库中,因此从MySQL控制台运行以下代码:

LOAD DATA LOCAL INFILE 'C:/<redacted>/data.csv' 
INTO TABLE tbl_data 
FIELDS TERMINATED BY ',' 
LINES TERMINATED BY '\n';

当包含NULL值的列被移动以便它不在最后一列时,此方法 可以正常工作,但是当数据为时,它会向我发出警告格式如上所示。

Query OK, 71735 rows affected, 49 warnings
' for column 'energy' at row 5253    |  value: 'N

我遵循this thread的建议,试图利用一个局部变量,但这并没有安抚MySQL神。

LOAD DATA LOCAL INFILE 'C:/<redacted>/data.csv' 
INTO TABLE tbl_data 
FIELDS TERMINATED BY ',' 
LINES TERMINATED BY '\n';
(time, device, voltage, amps, power, @energy)
SET energy = nullif(@energy,'\N')

哦,表结构是这样设置的,我正在运行MySQL 5.6.17:

+--------+-------------+-----+---------+
|NAME    |TYPE         |NULL | DEFAULT |
|time    |datetime     |No   | None    |
|device  |tinyint(1)   |No   | None    |
|voltage |smallint(3)  |No   | None    |
|amps    |decimal(6,3) |No   | None    |
|power   |decimal(6,3) |No   | None    |
|energy  |decimal(7,4) |Yes  | NULL    |
+--------+-------------+-----+---------+

我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

Rimas是正确的,我的初始陈述中的最后一个条款应该是:     由&#39; \ r \ n&#39;

终止的线路

relevant documentation的措辞如下:

  

如果您在Windows系统上生成了文本文件,则可能必须使用LINES TERMINATED BY&#39; \ r \ n&#39;正确读取文件,因为Windows程序通常使用两个字符作为行终止符。某些程序(如写字板)在编写文件时可能会使用\ r作为行终止符。要阅读此类文件,请使用LINES TERMINATED BY&#39; \ r&#39;。