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

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


当前回答

PSQL可以帮你做到这一点:

edd@ron:~$ psql -d beancounter -t -A -F"," \
                -c "select date, symbol, day_close " \
                   "from stockprices where symbol like 'I%' " \
                   "and date >= '2009-10-02'"
2009-10-02,IBM,119.02
2009-10-02,IEF,92.77
2009-10-02,IEV,37.05
2009-10-02,IJH,66.18
2009-10-02,IJR,50.33
2009-10-02,ILF,42.24
2009-10-02,INTC,18.97
2009-10-02,IP,21.39
edd@ron:~$

有关此处使用的选项的帮助,请参阅man 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用户是否了解如何创建要添加到社区版的分析小部件?

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'

我尝试了几件事,但很少有人能够给我所需的CSV与头细节。

以下是对我有效的方法。

psql -d dbame -U username \
  -c "COPY ( SELECT * FROM TABLE ) TO STDOUT WITH CSV HEADER " > \
  OUTPUT_CSV_FILE.csv

新版本- 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

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

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