Importing CSV and commas in string values

两盒软妹~` 提交于 2019-12-07 12:25:45

问题


I use postgres 8.4 and currently trying to import a trivial CSV:

Here is a table:

CREATE TABLE public.sample (
  a VARCHAR, 
  b VARCHAR
) WITHOUT OIDS;

and here is a csv file sample:

"foo","bar, baz"

The query

COPY sample FROM '/tmp/sample.csv' USING DELIMITERS ',';

expected throws

ERROR:  extra data after last expected column
CONTEXT:  COPY sample, line 1: ""foo","bar, baz""

But, well, CSV parsing is not a rocket science and I would wonder if it is not possible to solve without reformatting the source csv.

Any ideas?

PS: the csv comes from 3rd party, I cannot change the format.

PPS: yes, I understand I could pre-process it (change the delimiter manually) before I import it

Final solution:

COPY sample FROM '/tmp/sample.csv' WITH DELIMITER ',' CSV;

Originally taken from https://stackoverflow.com/a/9682174/251311, and documentation page is http://www.postgresql.org/docs/8.4/static/sql-copy.html


回答1:


Clearly you have a CSV file while you try to import it as text format. Use:

COPY sample FROM '/tmp/sample.csv' FORMAT CSV;

The default delimiter for CSV format is the comma (,) anyway. More in the manual. Syntax is for current version 9.1. For PostgreSQL 8.4:

COPY sample FROM '/tmp/sample.csv' CSV;


来源:https://stackoverflow.com/questions/10001651/importing-csv-and-commas-in-string-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!