从PostgreSQL将包含换行符的数据导出为CSV [英] Exporting data containing line feeds as CSV from PostgreSQL

查看:358
本文介绍了从PostgreSQL将包含换行符的数据导出为CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据从PostgreSQL导出到CSV。

I'm trying to export data From postgresql to csv.

首先,我创建了查询,并尝试使用文件->导出到CSV从pgadmin导出。 CSV是错误的,因为它包含例如:

First i created the query and tried exporting From pgadmin with the File -> Export to CSV. The CSV is wrong, as it contains for example :

标头:Field1; Field2; Field3; Field4

The header : Field1;Field2;Field3;Field4

现在,行开始很好,除了最后一个将它放在另一行的字段:

Now, the rows begin well, except for the last field that it puts it on another line:

示例:

Data1; Data2; Data3;

Data1;Data2;Data3;

Data4;

问题是我尝试尝试获取错误将数据导入另一台服务器。

The problem is i get error when trying to import the data to another server.

数据来自我创建的视图。

The data is From a view i created.

我也尝试过

COPY view(field1,field2...) TO 'C:\test.csv' DELIMITER ',' CSV HEADER;

它导出相同的文件。

我只想将数据导出到另一台服务器。

I just want to export the data to another server.

编辑:

尝试导入csv时出现错误:

When trying to import the csv i get the error :


错误:最后一个预期列之后的多余数据。上下文复制
操作,第3行:<< Data1,data2等。 >>

ERROR : Extra data after the last expected column. Context Copy actions, line 3: <<"Data1, data2 etc.">>

所以第一行是标题,第二行是第一行,数据减去最后一个字段,该行位于仅在第三行。

So the first line is the header, the second line is the first row with data minus the last field, which is on the 3rd line, alone.

推荐答案

为了将文件导出到另一台服务器中,您有两个选择:

In order for you to export the file in another server you have two options:


  • 在两台服务器之间创建一个共享文件夹,以便
    数据库也可以访问此目录。

复制(从your_table中选择field1,field2)到'[shared directory]'DELIMITER',CSV HEADER;


  • 使用$ b $的 STDOUT 触发目标服务器的导出b COPY 。使用 psql 可以通过运行以下
    命令来实现:

  • Triggering the export from the target server using the STDOUT of COPY. Using psql you can achieve this running the following command:

psql yourdb -c复制(从*表中选择*)到标准输出> output.csv

编辑:解决包含换行符的字段的问题( \ \n

EDIT: Addressing the issue of fields containing line feeds (\n)

如果您想删除换行符,请使用 REPLACE 函数。

In case you wanna get rid of the line feeds, use the REPLACE function.

示例:

 SELECT E'foo\nbar';
 ?column? 
----------
 foo     +
 bar
(1 Zeile)

删除换行符:

SELECT REPLACE(E'foo\nbaar',E'\n','');
 replace 
---------
 foobaar
(1 Zeile)

所以您的 COPY 应该看起来像这样:

So your COPY should look like this:

COPY (SELECT field1,REPLACE(field2,E'\n','') AS field2 FROM your_table) TO '[shared directory]' DELIMITER ',' CSV HEADER;

这篇关于从PostgreSQL将包含换行符的数据导出为CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆