简体   繁体   English

Postgres Psql 到文件

[英]Postgres Psql to file

I have a bash script, with a call to PSQL, which executes a query, and then using a WHILE loop, I print the output to a file.我有一个 bash 脚本,调用 PSQL,执行查询,然后使用 WHILE 循环,我将 output 打印到文件中。 Something like:就像是:

psql -U zrec -d zrec -t -c "SELECT .........;" \    | while read -a Record; do
  printf "${Record[0]},${Record[1]}\n"  >> /tmp/file.csv
done

The query has grown into a very large query.该查询已发展为一个非常大的查询。 Also, I now need to pass a date variable to the query.另外,我现在需要将日期变量传递给查询。 So, I'm thinking to take this hard coded query, and put it into a.sql file, call it, pass the date variable, and print the output to a file.因此,我正在考虑采用这个硬编码查询,并将其放入 .sql 文件中,调用它,传递日期变量,然后将 output 打印到文件中。

Oracle makes this easy with SPOOL and &1, etc....... Oracle 使用 SPOOL 和 &1 等使这变得容易......

Is there a way I can:有没有办法我可以:

  1. Call the bash script调用 bash 脚本
  2. Have the script call my_query.sql, and pass it a date parameter让脚本调用 my_query.sql,并传递一个日期参数
  3. Put the query output into a file将查询 output 放入文件

Seems like it should be simple, but is proving not to be.看起来应该很简单,但事实证明并非如此。

If you want to generate a csv file, don't use spool or something similar, use \copy .如果要生成csv文件,请不要使用 spool 或类似的东西,请使用\copy No need to loop.无需循环。

Something like:就像是:

\copy (SELECT ....) to '/tmp/file.csv' with (format csv, header true)

It's typically easier to put anything that is longer than a few words into a separate SQL script rather than passing it using -c "..." which also opens up many nested quoting problems.将比几个单词更长的任何内容放入单独的 SQL 脚本中通常更容易,而不是使用-c "..."传递它,这也会引发许多嵌套引用问题。

So if you put the above into a file eg export.sql , all you need is:因此,如果您将上述内容放入文件中,例如export.sql ,您只需要:

psql -U zrec -d zrec -f export.sql`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM