psql-编写查询并将查询的输出保存到文件中 [英] psql - write a query and the query's output to a file

查看:807
本文介绍了psql-编写查询并将查询的输出保存到文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Postgresql 9.3.1中,使用 psql 命令交互式开发查询时,最终结果有时是将查询结果写入文件:

  boron.production => / / tmp / output 
boron.production =>选择1;
boron.production => \ o
boron.production => \q
$ cat / tmp / output
?列?
----------
1
(1行)

这很好。但是,如何获取查询本身与查询结果一起写入文件?



我尝试为psql提供-回声查询开关:

  -e,--echo- querys 
也将所有发送到服务器的SQL命令复制到标准输出。
这等效于将变量ECHO设置为查询。

但这总是回显到stdout,而不是我使用\o命令给出的文件。 / p>

我也尝试了-echo-all 开关,但它似乎没有回显交互式输入。



使用命令编辑,我可以在前面加上 \qecho 来重复查询。可以,但是很乏味。



有什么方法可以指导交互式psql会话将查询和查询输出都写到文件中?

解决方案

您可以尝试直接将标准输出从外壳重定向到文件(Win或Linux应该可以使用)

  psql -U postgres -c选择1作为结果 -e nomedb> hello.txt 

这样做的缺点是无法交互查看输出。如果存在问题,则可以将输出文件拖到单独的终端中,或者在* nix中使用 tee 实用程序:

  psql -U postgres -c选择1作为结果 -e nomedb | tee hello.txt 

希望这会有所帮助!



Luca


In postgresql 9.3.1, when interactively developing a query using the psql command, the end result is sometimes to write the query results to a file:

boron.production=> \o /tmp/output
boron.production=> select 1;
boron.production=> \o
boron.production=> \q
$ cat /tmp/output
?column? 
----------
        1
(1 row)

This works fine. But how can I get the query itself to be written to the file along with the query results?

I've tried giving psql the --echo-queries switch:

   -e, --echo-queries
       Copy all SQL commands sent to the server to standard output as well.
       This is equivalent to setting the variable ECHO to queries.

But this always echoes to stdout, not to the file I gave with the \o command.

I've tried the --echo-all switch as well, but it does not appear to echo interactive input.

Using command editing, I can repeat the query with \qecho in front of it. That works, but is tedious.

Is there any way to direct an interactive psql session to write both the query and the query output to a file?

解决方案

You can try redirecting the stdout to a file directly from your shell (Win or Linux should work)

psql -U postgres -c "select 1 as result" -e nomedb >> hello.txt

This has the drawback of not letting you see the output interactively. If that's a problem, you can either tail the output file in a separate terminal, or, if in *nix, use the tee utility:

psql -U postgres -c "select 1 as result" -e nomedb | tee hello.txt

Hope this helps!

Luca

这篇关于psql-编写查询并将查询的输出保存到文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆