我从第一列的CSV文件中获取MySQL中导入的所有数据。所有其他列都获取NULL值

时间:2016-06-20 19:26:03

标签: mysql mysqlimport

我在本地使用MySQL到我的Mac。 我有一个CSV文件,所有字段都用双引号括起来。 以下是我的CSV文件的第一行摘录:

$ head -5 companies.csv
"COMPANY_ADDRESS1","COMPANY_ADDRESS2","COMPANY_CITY","COMPANY_COUNTRY","COMPANY_FAX","COMPANY_GERMANY","COMPANY_ID","COMPANY_INDIANAPOLIS","COMPANY_NAME","COMPANY_STATE","COMPANY_TELEPHONE","COMPANY_VAT","COMPANY_ZIP"
"980 Madison Avenue","6th Floor","New York","USA","","","1393","","Lucky Fives LLC","NY","212-74-2313","","10075"
"1209 Orange Street","","Wilmington","USA","","","1394","","Global Five Holdings","DE","-","","19801"
"2020 Ponce de Leon Boulevard","PH2","Coral Gables","USA","","1015110","1395","","Lion Aero Corporation","FL","305-755-5120","","33134"
"100 NE Adams Street","","Peoria","USA","","","1396","","Caterpillar Inc.","IL","+13096755975","","61630"

这是我的导入命令:

$ mysqlimport --local --ignore-lines=1 my_db companies.csv -u root --fields-enclosed-by='\"' --lines-terminated-by='\r\n' --fields-terminated-by=','

我将导入所有记录,不会跳过任何内容:

companies: Records: 3063  Deleted: 0  Skipped: 0  Warnings: 104

但是,为什么我在第一列中导入所有数据而所有其他列都填充了NULL?

此表先前已创建,其中包含支持要加载的数据所需的所有列。

2 个答案:

答案 0 :(得分:2)

我认为mysqlimport正在寻找一个反斜杠双引号来封闭字段,并且没有找到任何字段,因此它只是一个字段。

我在双引号之前质疑反斜杠字符的用途。如果这是针对Linux bash shell的,我认为不需要反斜杠来指定双引号。作为演示:

# echo foo --fields-enclosed-by='\"'
foo --fields-enclosed-by=\"

# echo foo --fields-enclosed-by='"'
foo --fields-enclosed-by="

(这只是一个猜测,我可能是错的。我之前已经错过了很多次。有可能mysqlimport丢弃了传递给它的反斜杠字符。问题可能是其他问题。但是对于测试,如果没有反斜杠的话,我会给它旋转,看看没有它的烟雾有多大。)

演示环境:

# uname -o -r -s
Linux 3.13.0-83-generic GNU/Linux

# echo $SHELL
/bin/bash

答案 1 :(得分:1)

测试架构:

-- drop table if exists aT;
create table aT
(   -- address thing
    COMPANY_ADDRESS1 varchar(100) not null,
    COMPANY_ADDRESS2 varchar(100) not null,
    COMPANY_CITY varchar(100) not null,
    COMPANY_COUNTRY varchar(100) not null,
    COMPANY_FAX varchar(100) not null,
    COMPANY_GERMANY varchar(100) not null,
    COMPANY_ID varchar(100) not null,
    COMPANY_INDIANAPOLIS varchar(100) not null,
    COMPANY_NAME varchar(100) not null,
    COMPANY_STATE varchar(100) not null,
    COMPANY_TELEPHONE varchar(100) not null,
    COMPANY_VAT varchar(100) not null,
    COMPANY_ZIP varchar(100) not null
);

命令以交互方式或通过程序运行:

LOAD DATA INFILE 'c:\\nate\\aT.csv' INTO TABLE aT
  FIELDS TERMINATED BY ',' ENCLOSED BY '"'
  LINES TERMINATED BY '\r\n'
  IGNORE 1 LINES;
select * from aT;

or Linux:

LOAD DATA INFILE '/home/nate/aT.csv' INTO TABLE aT
  FIELDS TERMINATED BY ',' ENCLOSED BY '"'
  LINES TERMINATED BY '\n'
  IGNORE 1 LINES;

将数据带入

没问题

从aT中选择*; - 查看导入

现在用于命令行(创建上述之一的.sql):

truncate aT; -- run this first

mysql -u root -p so_gibberish2 < c:\nate\run_this1.sql

so_gibberish2是数据库名称。数据进来。因为mysql客户端不受bash或其他命令行转义序列的影响。