如何将 PostgreSQL 中的结果数据导出到 .CSV?

How to export the resulting data in PostgreSQL to .CSV?

我使用 PostgreSQL 9.4.1

我的查询:

copy(select * from city) to 'C:\temp\city.csv'
copy(select * from city) to E'C:\temp\city.csv'

ERROR: relative path not allowed for COPY to file ********** Error **********

ERROR: relative path not allowed for COPY to file SQL state: 42602

psql 中的 this case, it seems likely that you are attempting to use copy from a computer other than the one which hosts your database. copy does I/O from the database host machine's local file system only. If you have access to that filesystem, you can adjust your attempt accordingly. Otherwise, you can use the \copy 命令一样。

可能会迟到,但我认为它会有所帮助。

  1. 在 Windows 上,确保输出目录已获得 Everyone(或者您可以指定用户名)的 read/write 权限。
  2. 使用 斜杠 (/) 代替反斜杠 (),示例

COPY DT1111 TO 'D:/TEST/DT1111_POST.CSV' DELIMITER ',' CSV HEADER;

我正在使用 pgAdmin v1.5。第一个查询是

select table_name from information_schema.tables where table_catalog = 'ofbiz' order by table_name

然后我按下按钮下载,pgAdmin 将 return 一个 csv 文件,是第一次查询的结果集。

TLDR:确保您在 copy-to 位置也有写入权限!

我遇到了完全相同的第一个错误,ERROR: relative path not allowed for COPY to file,即使我使用了 '/tmp/db.csv'(这不是相对路径)。

就我而言,错误消息非常具有误导性,因为我在主机上,有一个绝对文件路径并且该位置存在。我的问题是我使用了 bitnami postgres:12 docker 图像,容器中的 tmp 文件夹属于 root 那里,而 postgres 和 psql 使用 postgres 用户。我的解决方案是在那里创建一个导出文件夹并将所有权转换为 postgres 用户:

mkdir /tmp/export
chown postgres:postgres /tmp/export

然后就可以COPY tablename TO '/tmp/export/db.csv';使用成功了