简体   繁体   中英

Import CSV file via PSQL With Array Values

I have a very simple table where I would like to insert data from a CSV into it.

create table products(
  id integer primary key,
  images text[]
);

Here is what I am currently trying with my csv:

1,"['hello.jpg', 'world.jpg']"
2,"['hola.jpg', 'mundo.jpg']"

When I do the following, I get a syntax error from psql, with no additional information what could have gone wrong.

\copy products 'C:\Users\z\Downloads\MOCK_DATA.csv' WITH DELIMITER ',';

Does anyone know how to format my array values properly?

If you remove the square brackets from the csv file then I would have the table like this ( images as text rather than text[] ):

create table products_raw
(
  id integer primary key,
  images text
);

plus this view

create view products as 
  select id, ('{'||images||'}')::text[] as images 
  from products_raw;

and use the view henceforth. Anyway I would rather have the CSV file like this, no formatting, just data:

1,"hello.jpg,world.jpg"
2,"hola.jpg,mundo.jpg"

It is also worth considering to attach the csv file as a foreign table using file_fdw . It is a bit more complicated but usually pays off with several benefits.

You can add headers to your CSV and use CSV to SQL converters like this and copy it to TEMPORARY TABLE and if the data does not need to be sanitized, then you are good to go. In case you are not using pgAdmin , please, it makes things way handier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM