将csv文件加载到mysql数据库中

时间:2016-01-12 15:47:49

标签: mysql csv mysql-workbench workbench mysqlimport

我试图将一个大的CSV文件加载到mysql中,但无法找出它失败的原因。

我的CSV文件如下所示:

_id,"event","unit","created","r1","r2","r3","r4","space_id","owner_id","name","display_name","users__email"
565ce313819709476d7eaf0e,"create",3066,"2015-12-01T00:00:19.604Z","563f592dd6f47ae719be8b38","3","13","7","55ecdd4ea970e6665f7e3911","55e6e3f0a856461404a60fc1","household","household","foo.bar@ace.com"
565ce350819709476d7eaf0f,"complete",3067,"2015-12-01T00:01:19.988Z","21","","","","55e6df3ba856461404a5fdc9","55e6e3f0a856461404a60fc1","Ace","Base","foo.bar@ace.com"
565ce350819709476d7eaf0f,"delete",3067,"2015-12-01T00:01:19.988Z","21","","","","55e6df3ba856461404a5fdc9","55e6e3f0a856461404a60fc1","Ace","Base","foo.bar@ace.com"
565ce350819709476d7eaf0f,"update",3067,"2015-12-01T00:01:19.988Z","21","","","","55e6df3ba856461404a5fdc9","55e6e3f0a856461404a60fc1","Ace","Base","foo.bar@ace.com"

我的代码将文件加载到mysql就是这个:

CREATE DATABASE IF NOT EXISTS analys;

USE analys;

CREATE TABLE IF NOT EXISTS event_log (
  _id CHAR(24) NOT NULL,
  event_log VARCHAR(255),
  unit CHAR(4),
  created VARCHAR(255),
  r1 VARCHAR(255),
  r2 VARCHAR(255),
  r3 VARCHAR(255),
  r4 VARCHAR(255),
  space_id VARCHAR(255),
  owner_id VARCHAR(255),
  name VARCHAR(255),
  display_name VARCHAR(255),
  users__email VARCHAR(255),
  PRIMARY KEY (_id)
)

LOAD DATA INFILE 'audits.export.csv' 
INTO TABLE event_log
FIELDS TERMINATED BY ',' 
ENCLOSED BY '"'
LINES TERMINATED BY '\n\r'
IGNORE 1 ROWS;

一切都很好,包括查询,但我在每一列(只有一行)中得到NULL

以下是行动输出:

22:31:21    LOAD DATA INFILE 'audits.export.csv'  INTO TABLE event_log FIELDS TERMINATED BY ','  ENCLOSED BY '"' LINES TERMINATED BY '\n\r' IGNORE 1 ROWS   0 row(s) affected Records: 0  Deleted: 0  Skipped: 0  Warnings: 0   0.156 sec

我尝试调整表格和加载查询,但它不起作用

我在Windows 7上使用Mysql 5.6和Workbench。 我在这里听说过GUI解决方案或Excel连接器(Excel Connector),但我更喜欢以编程方式进行,因为我需要重用代码。

有任何帮助吗?我无法通过Stackoverflow上的类似帖子解决问题。

2 个答案:

答案 0 :(得分:0)

这似乎不是一个有效的换行符:

LINES TERMINATED BY '\n\r'

更改为:

LINES TERMINATED BY '\r\n'

或者只有其中一个(可以是单\n\r,具体取决于系统或创建csv文件的软件。)

答案 1 :(得分:0)

因为有些人可能想知道如何使用MySQL Workbench做到这一点:

  1. 将CSV数据保存到文件,例如foo.csv
  2. 打开MySQL Workbench
  3. 选择/打开MySQL连接
  4. 右键单击对象浏览器(左侧导航器)中的架构
  5. 选择“表数据导入向导”
  6. 选择CSV文件,在我们的示例中为foo.csv
  7. 按照向导;许多配置选项都可用,包括分隔符
  8. 完成后,CSV数据将显示在新表或现有表中(您的选择)
  9. 有关其他信息,请参阅标题为Table Data Export and Import Wizard的文档。

    我刚刚在问题中提供的示例数据中对此进行了测试,并且有效。