将查询结果转换为 CSV

Converting query result into CSV

我有一个 JDBI 查询,returns 我需要将几个表中的许多列写入 CSV 文件。我怎样才能做到这一点?我有一个接收 POST 搜索条件的 REST 端点,我正在使用它构建一个查询以触发 Postgres 数据库。我正在使用 Dropwizard 和 JDBI。

使用COPY TO.

COPY (SELECT ... ) TO '/path/to/myfile1.csv' FORMAT csv;

如果要写入文件,您需要超级用户权限。 The manual:

COPY naming a file or command is only allowed to database superusers, since it allows reading or writing any file that the server has privileges to access.

或者您可以直接将输出发送到 STDOUT 而无需保存到文件(可能没有超级用户权限!)。

要在您的客户端(可以与数据库服务器分开或不分开)写入文件,请使用元命令 \copy of psql encapsulating the same functionality. This does not require superuser privileges:

This means that file accessibility and privileges are those of the local user, not the server, and no SQL superuser privileges are required.

详情:

  • PostgreSQL: export resulting data from SQL query to Excel/CSV