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

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


当前回答

新版本- psql 12 -将支持——csv。

PSQL - devel ——csv 切换到CSV(逗号分隔值)输出模式。这相当于\pset格式的csv。 csv_fieldsep 指定在CSV输出格式中使用的字段分隔符。如果分隔符出现在字段的值中,该字段将以双引号输出,遵循标准CSV规则。默认值是逗号。

用法:

psql -c "SELECT * FROM pg_catalog.pg_tables" --csv  postgres

psql -c "SELECT * FROM pg_catalog.pg_tables" --csv -P csv_fieldsep='^'  postgres

psql -c "SELECT * FROM pg_catalog.pg_tables" --csv  postgres > output.csv

其他回答

从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

如果你有更长的查询,你喜欢使用psql,然后把你的查询到一个文件,并使用以下命令:

psql -d my_db_name -t -A -F";" -f input-file.sql -o output-file.csv

在终端(当连接到db时)将输出设置为cvs文件

1)设置字段分隔符为',':

\f ','

2)设置输出格式不对齐:

\a

3)只显示元组:

\t

4)设定输出:

\o '/tmp/yourOutputFile.csv'

5)执行查询:

:select * from YOUR_TABLE

6)输出:

\o

然后,您将能够在这个位置找到您的csv文件:

cd /tmp

使用scp命令复制或使用nano编辑:

nano /tmp/yourOutputFile.csv

应@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用户是否了解如何创建要添加到社区版的分析小部件?

import json
cursor = conn.cursor()
qry = """ SELECT details FROM test_csvfile """ 
cursor.execute(qry)
rows = cursor.fetchall()

value = json.dumps(rows)

with open("/home/asha/Desktop/Income_output.json","w+") as f:
    f.write(value)
print 'Saved to File Successfully'