从PostgreSQL数据库保存PL/pgSQL输出到CSV文件的最简单的方法是什么?
我使用PostgreSQL 8.4 pgAdmin III和PSQL插件,我从那里运行查询。
从PostgreSQL数据库保存PL/pgSQL输出到CSV文件的最简单的方法是什么?
我使用PostgreSQL 8.4 pgAdmin III和PSQL插件,我从那里运行查询。
当前回答
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'
其他回答
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'
应@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
有几种解决方案:
1 PSQL命令
psql -d dbname -t -A -F"," -c "select * from users" > output.csv
这有一个很大的优势,您可以通过SSH使用它,如SSH postgres@host命令-使您能够获得
2 postgres copy命令
拷贝(SELECT * from users)到'/tmp/output.csv'
PSQL交互(或不交互)
>psql dbname
psql>\f ','
psql>\a
psql>\o '/tmp/output.csv'
psql>SELECT * from users;
psql>\q
它们都可以在脚本中使用,但我更喜欢第1种。
4 pgadmin,但这是不可编写脚本的。
下载列名为HEADER的CSV文件使用以下命令:
Copy (Select * From tableName) To '/tmp/fileName.csv' With CSV HEADER;