正确的COPY命令加载从具有单引号CSV文件PostgreSQL的数据?(The correct C

2019-08-01 09:19发布

我有了这样的内容CSV文件:

10,53073,0,0,'Y','2008-05-30 21:46:55',0,'2008-05-30 21:48:04',0,53071,2

我想CSV数据加载到MY_TABLE。

CREATE TABLE my_table
(
  ad_tree_id numeric(10,0) NOT NULL,
  node_id numeric(10,0) NOT NULL,
  ad_client_id numeric(10,0) NOT NULL,
  ad_org_id numeric(10,0) NOT NULL,
  isactive character(1) NOT NULL DEFAULT 'Y'::bpchar,
  created timestamp without time zone NOT NULL DEFAULT now(),
  createdby numeric(10,0) NOT NULL,
  updated timestamp without time zone NOT NULL DEFAULT now(),
  updatedby numeric(10,0) NOT NULL,
  parent_id numeric(10,0),
  seqno numeric(10,0),
  CONSTRAINT ad_treenodemm_pkey PRIMARY KEY (ad_tree_id , node_id ),
  CONSTRAINT adtree_adtreenodemm FOREIGN KEY (ad_tree_id)
      REFERENCES ad_tree (ad_tree_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE DEFERRABLE INITIALLY DEFERRED,
  CONSTRAINT ad_treenodemm_isactive_check CHECK (isactive = ANY (ARRAY['Y'::bpchar, 'N'::bpchar]))
)

当我运行中的pgAdmin III工具下面的命令:

COPY my_table FROM 'c:\downloads\file.csv' DELIMITERS ',' CSV;

我得到的错误:

ERROR:  value too long for type character(1)
CONTEXT:  COPY my_table, line 1, column isactive: "'Y'"

然后我修改的命令是这样的:

COPY my_table FROM 'c:\downloads\file.csv' DELIMITERS ',' CSV QUOTE ''';
COPY my_table FROM 'c:\downloads\file.csv' DELIMITERS ',' CSV QUOTE '\'';
COPY my_table FROM 'c:\downloads\file.csv' DELIMITERS ',' CSV QUOTE '\'' ESCAPE '\';
COPY my_table FROM 'c:\downloads\file.csv' DELIMITERS ',' CSV QUOTE '\'' ESCAPE \;

当尝试都失败。

所以,任何人都可以告诉我这种情况的正确COPY命令?

Answer 1:

双单引号(如果standard_conforming_strings上,看到的文档 )

COPY my_table FROM 'c:\downloads\file.csv' DELIMITERS ',' CSV QUOTE '''';

或者使用非标准的PostgreSQL相关转义字符串 :

COPY my_table FROM 'c:\downloads\file.csv' DELIMITERS ',' CSV QUOTE E'\'';


Answer 2:

谁遇到这个错误另一些人可能要检查的文件,看它是否包含在第一行的标题。 虽然这不是你的情况的问题,值得注意的是解决它的方法:

COPY my_table FROM 'c:\downloads\file.csv' WITH DELIMITER ',' CSV HEADER;


Answer 3:

没关系,我得到了答案:

COPY my_table FROM 'c:\downloads\file.csv' DELIMITERS ',' CSV QUOTE '''';


文章来源: The correct COPY command to load postgreSQL data from csv file that has single-quoted data?