正确的COPY命令从包含单引号数据的csv文件加载PostgreSQL数据?

ftf50wuq  于 2023-02-27  发布在  PostgreSQL
关注(0)|答案(4)|浏览(123)

我有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命令?

yftpprvb

yftpprvb1#

双单引号(如果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'\'';
ql3eal8s

ql3eal8s2#

遇到此错误的其他一些人可能希望检查文件,看看它是否在第一行包含标题。虽然这不是您的情况下的问题,但值得注意的是解决方法:

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

h7appiyu3#

没关系,我得到了答案:

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

bwntbbo34#

如果.csv文件中的列数据用双引号括起来,并以,分隔,请使用此选项

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

相关问题