postgresql - 将查询结果转换为 CSV

标签 postgresql csv jdbc dropwizard jdbi

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

最佳答案

使用COPY TO .

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

如果你想写入一个文件,你需要 super 用户权限。 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 而无需保存到文件(可能没有 super 用户权限!)。

要在您的客户端(可以与数据库服务器分开或不分开)写入文件,请使用元命令 \copy of psql封装相同的功能。这确实 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 - 将查询结果转换为 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36634828/

相关文章:

c# - 在 JSON 中不支持 bigint

postgresql - 用于 PostgreSQL 通知/监听的 .NET 库

sql - 如何在 PostgreSQL 中仅 self 加入一部分行?

php - 如何从 CSV 文件中拆分 php 中的字符串并插入数据库中的多行?

python - 自定义数据集的 ImageDataGenerator 的替代方案

java - 项目 > 1000 的 SQL in 子句

postgresql - 从函数返回 SELECT 结果作为 JSON (Postgres)

javascript - 使用 jQuery-csv 解析 csv 数据

java - 带有多个paramsin java mysql的PreparedStatement问题

java - JDK中是否包含jdbc api?