将查询和查询结果输出到文件 - psql

15

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

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

这个工作正常。但是我如何将查询本身与查询结果一起写入文件?

我尝试使用--echo-queries开关来运行psql:

   -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.

但是这总是回显到标准输出,而不是我用 \o 命令给出的文件。

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

使用命令编辑,我可以在查询前面加上 \qecho 来重复查询。那样可以,但很繁琐。

有没有办法将交互式 psql 会话定向到一个文件中,同时写入查询和查询输出?


1
\o 命令将查询 结果 输出到输出文件中... 我不知道如何实现。您可以使用 \qecho 将文本放入输出中... 或者您可以批处理运行 SQL - 使用重定向。然后 -e 将起作用。 - Kamil Šrot
3个回答

20

你可以尝试从你的Shell(无论是Windows还是Linux)直接将stdout重定向到文件中。

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

这种方法的缺点是不能使你与输出内容实时交互。如果这是个问题,你可以在另一个终端中使用tail命令来查看输出文件,或者在*nix系统中使用tee工具:

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
希望这有所帮助!
Luca

我刚刚意识到,通过添加“tee”,这个答案非常好地回答了我的问题,所以我冒昧编辑了答案,展示如何使用“tee”;因此,我将长期拖欠的勾选标记授予了您。感谢您的回答! - Wayne Conrad

6

我知道这是一个老问题,但至少在9.3和当前版本中,可以使用查询缓冲区元命令(在文档中显示)或psql控制台中的\?来实现。链接如下:https://www.postgresql.org/docs/9.3/static/app-psql.html

\w or \write filename
\w or \write |command

Outputs the current query buffer to the file filename or pipes it to the shell command command.

1
感谢您帮助解决这个老问题。\w(又称为\write)命令会写入之前的命令,但不包括它们的输出(在psql 9.4.8中测试过)。实际想要的是将未来的命令及其输出写入。尽管如此,考虑到我们目前必须使用其他方法来实现我的目标,这仍然是一个很好的命令需要了解。 - Wayne Conrad

0
请尝试使用这个格式,因为我从中得到了输出:
psql -h $host -p $port -q -U $user -d $Dbname -c "SELECT \"Employee-id\",\"Employee-name\" FROM Employee_table" >> Employee_Date.csv

我需要将输出保存为CSV文件。


在你的 psql 参数中添加 --csv - rosmcmahon

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接