将CSV加载到MySQL Workbench表中

时间:2014-02-13 14:25:20

标签: mysql sql csv

以下是原始csv的片段(来自Quandl):

Date,Open,High,Low,Close,Volume_BTC,Volume_Dollar,Weighted_Price
13/02/2014,650.04,660,645.07,645.24,4027.229102,2628148.177,652.5946528
12/02/2014,677,685.19,631.58,651.99,15511.78726,10224606.46,659.1507667

这是我正在尝试的SQL代码,其中我尝试了许多排列:

load data local infile '/../BITSTAMPUSD.csv' 
into table test.BTC  
CHARACTER SET utf8
FIELDS TERMINATED BY ','
enclosed by ""
LINES TERMINATED BY '\n'
IGNORE 1 LINES;

以下是我遇到的错误:

1 row(s) affected, 8 warning(s): 1265 Data truncated for column 'Date' at row 1 1265 Data truncated for column 'Open' at row 1 1265 Data truncated for column 'High' at row 1 1265 Data truncated for column 'Low' at row 1 1265 Data truncated for column 'Close' at row 1 1265 Data truncated for column 'Volume_BTC' at row 1 1265 Data truncated for column 'Volume_Dollar' at row 1 1265 Data truncated for column 'Weighted_Price' at row 1 Records: 1  Deleted: 0  Skipped: 0  Warnings: 8

这是我用来生成表的代码:

CREATE TABLE BTC(
    Date DATE,  
    Open FLOAT,
    High FLOAT,
    Low FLOAT,
    Close FLOAT,    
    Volume_BTC FLOAT,
    Volume_Dollar FLOAT,
    Weighted_Price FLOAT
)

我已经在这个问题上打了一段时间了,所以任何帮助都非常感谢。

更新:我已经尝试了一些建议,仍然没有修复。我怀疑它与线路终止有关。我使用Mac是有所作为的。 '/ n'是否正确?

2 个答案:

答案 0 :(得分:1)

您可以在导入字段时使用str_to_date转换字段,例如此示例中最后两行添加到您的代码中:

load data local infile '/../BITSTAMPUSD.csv' 
into table BTC  
CHARACTER SET utf8
FIELDS TERMINATED BY ','
enclosed by ""
LINES TERMINATED BY '\r'
IGNORE 1 LINES
(@date,Open,High,Low,Close,Volume_BTC,Volume_Dollar,Weighted_Price)
SET `Date` = DATE_FORMAT(STR_TO_DATE(@date, '%d/%m/%Y'), '%Y/%m/%d');

对于Mac我也认为你需要使用'\ r'来终止行。

我确实尝试创建你的表并导入一个包含你数据的文件,它可以正常使用上面的“加载数据”查询。因此线路终端可能是唯一缺失的......

答案 1 :(得分:1)

LINES TERMINATED BY '\n'更改为LINES TERMINATED BY '\r'解决了我的问题!

对于Windows使用'\ n',对于mac使用'\ n'。