从PostgreSQL数据库保存PL/pgSQL输出到CSV文件的最简单的方法是什么?

我使用PostgreSQL 8.4 pgAdmin III和PSQL插件,我从那里运行查询。


当前回答

应@skeller88的要求,我将我的评论作为一个答案重新发布,这样就不会被那些没有阅读每个回复的人所遗漏……

DataGrip的问题在于它控制了你的钱包。它不是免费的。在DBeaver .io上试试社区版的DBeaver。它是一个面向SQL程序员、dba和分析师的自由/开源多平台数据库工具,支持所有流行的数据库:MySQL、PostgreSQL、SQLite、Oracle、DB2、SQL Server、Sybase、MS Access、Teradata、Firebird、Hive、Presto等。

DBeaver Community Edition使得连接到数据库、发出查询以检索数据、然后下载结果集以将其保存为CSV、JSON、SQL或其他常见数据格式变得非常简单。对于Postgres的TOAD, SQL Server的TOAD,或者Oracle的TOAD,它是一个可行的自由/开源软件竞争对手。

I have no affiliation with DBeaver. I love the price and functionality, but I wish they would open up the DBeaver/Eclipse application more and made it easy to add analytics widgets to DBeaver / Eclipse, rather than requiring users to pay for the annual subscription to create graphs and charts directly within the application. My Java coding skills are rusty and I don't feel like taking weeks to relearn how to build Eclipse widgets, only to find that DBeaver has disabled the ability to add third-party widgets to the DBeaver Community Edition.

DBeaver用户是否了解如何创建要添加到社区版的分析小部件?

其他回答

我写了一个叫做psql2csv的小工具,它封装COPY查询TO STDOUT模式,生成合适的CSV。它的接口类似于psql。

psql2csv [OPTIONS] < QUERY
psql2csv [OPTIONS] QUERY

查询被假定为STDIN的内容(如果存在)或最后一个参数。所有其他参数都被转发到psql,除了以下参数:

-h, --help           show help, then exit
--encoding=ENCODING  use a different encoding than UTF8 (Excel likes LATIN1)
--no-header          do not output a header

在pgAdmin III中,有一个从查询窗口导出到文件的选项。在主菜单中,它是Query -> Execute to file或者有一个按钮做同样的事情(它是一个带有蓝色软盘的绿色三角形,而不是仅仅运行查询的普通绿色三角形)。如果您没有从查询窗口运行查询,那么我将按照IMSoP的建议使用复制命令。

下载列名为HEADER的CSV文件使用以下命令:

Copy (Select * From tableName) To '/tmp/fileName.csv' With CSV HEADER;

应@skeller88的要求,我将我的评论作为一个答案重新发布,这样就不会被那些没有阅读每个回复的人所遗漏……

DataGrip的问题在于它控制了你的钱包。它不是免费的。在DBeaver .io上试试社区版的DBeaver。它是一个面向SQL程序员、dba和分析师的自由/开源多平台数据库工具,支持所有流行的数据库:MySQL、PostgreSQL、SQLite、Oracle、DB2、SQL Server、Sybase、MS Access、Teradata、Firebird、Hive、Presto等。

DBeaver Community Edition使得连接到数据库、发出查询以检索数据、然后下载结果集以将其保存为CSV、JSON、SQL或其他常见数据格式变得非常简单。对于Postgres的TOAD, SQL Server的TOAD,或者Oracle的TOAD,它是一个可行的自由/开源软件竞争对手。

I have no affiliation with DBeaver. I love the price and functionality, but I wish they would open up the DBeaver/Eclipse application more and made it easy to add analytics widgets to DBeaver / Eclipse, rather than requiring users to pay for the annual subscription to create graphs and charts directly within the application. My Java coding skills are rusty and I don't feel like taking weeks to relearn how to build Eclipse widgets, only to find that DBeaver has disabled the ability to add third-party widgets to the DBeaver Community Edition.

DBeaver用户是否了解如何创建要添加到社区版的分析小部件?

从Postgres 12开始,你可以改变输出格式:

\pset format csv

允许使用以下格式:

aligned, asciidoc, csv, html, latex, latex-longtable, troff-ms, unaligned, wrapped

如果要导出请求的结果,可以使用\o文件名特性。

例子:

\pset format csv

\o file.csv
SELECT * FROM table LIMIT 10;
\o

\pset format aligned