简体   繁体   English

通过带有数组值的 PSQL 导入 CSV 文件

[英]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.我有一个非常简单的表,我想将 CSV 中的数据插入其中。

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

Here is what I am currently trying with my csv:这是我目前正在尝试使用 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.当我执行以下操作时,我从 psql 收到语法错误,没有其他信息可能出了什么问题。

\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[] ):如果您从csv文件中删除方括号,那么我将拥有这样的表格( images作为text而不是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:无论如何,我宁愿拥有这样的 CSV 文件,没有格式化,只有数据:

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 .还值得考虑使用file_fdw将 csv 文件附加为 外部表 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. 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.如果您不使用pgAdmin ,请让事情变得更方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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