将PostgreSQL查询结果存储到Shell或PostgreSQL变量 [英] Store PostgreSQL query result to Shell or PostgreSQL variable

查看:1013
本文介绍了将PostgreSQL查询结果存储到Shell或PostgreSQL变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个表存储值:

For instance, I have a table stores value:

select * from myvalue;

  val
-------
 12345
(1 row)

如何将 12345 保存到Postgresql或Shell脚本中的变量中?

How can I save this 12345 into a variable in postgresql or shell script?

这是我在shell脚本中尝试过的操作:

Here's what I tried in my shell script:

var=$(psql -h host -U user -d db <<SQLSTMT
SELECT * FROM myvalue;
SQLSTMT)

但是 echo $ var 给我:

val ------- 12345 (1 row)

我也尝试过

\set var (select * from myvalue)

在psql中,当我键入 \set 时,它会列出:

in psql and when I type \set it lists:

var = '(select*frommyvalue)'


推荐答案

不,不,不!使用psql中的原始数据开关(例如 -t或 \t),并将查询通过管道传递给psql,而不是解析ascii-table,请执行:-)

No, no, no! Use "raw data" switch from psql, like "-t" or "\t" and pipe the query to psql instead of parsing ascii-table, come on :-)

echo 'select * from myvalue;' | psql -t -h host -U user -d db

如果您确实需要解析psql输出,则可以也可以使用-H开关(打开HTML输出),并使用一些perl模块来解析html表,我曾经使用过它一两次。此外,您可能希望使用 pgpass文件 〜/ .psqlrc 用于某些默认设置,例如未指定时连接的默认DB

If you really need parse psql output, you could also use -H switch ( turns on HTML output ), and parse it with some perl module for parsing html tables, I used that once or twice.. Also, you may want to use a pgpass file and ~/.psqlrc for some defaults, like default DB to connect, when not specified.

这篇关于将PostgreSQL查询结果存储到Shell或PostgreSQL变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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