Bash脚本和PostgreSQL:如何访问从SELECT语句返回的colunm值.

Rob*_*ens 3 sql postgresql bash

我在PostgreSQL中有一个名为customers的数据库,客户有一个名为CustomerInfo的表.CustomerInfo包含3个colunms ID,名称和地址.我想编写一个bash脚本来从CustomerInfo表中获取信息,但是一旦得到查询结果,我不知道如何访问各行.这是我写的脚本:

#!/bin/bash  

results=`psql -d customers -c "select * from CustomerInfo where name = 'Dave'"`

echo $results['name']
Run Code Online (Sandbox Code Playgroud)

查询正确运行并返回正确的结果,但echo命令将只打印结果中的所有内容.我知道这不是正确的方法,有没有人知道将查询结果作为数组的方法,或者我只需编写自己的函数来解析结果?

谢谢!

小智 8

您可以将结果存储到数组中并使用while循环遍历它.

psql -d customers -c "select * from CustomerInfo where name = 'Dave'"
| while read -a Record ; do
    # ${Record[0]} is your ID field
    # ${Record[1]} is your Name field
    # ${Record[2]} is your address field
done
Run Code Online (Sandbox Code Playgroud)


yok*_*eho 6

我成功地使用了

psql | while read do 
Run Code Online (Sandbox Code Playgroud)

方法:

$PG_HOME/bin/psql \
-h 127.0.0.1 \
-U $DB_USER \
-c 'SELECT recipient_email, name FROM report_recipients' \
--set ON_ERROR_STOP=on \
--no-align \
--quiet \
--no-password \
--tuples-only \
--field-separator ' ' \
--pset footer=off \
--dbname=$DATABASE \
| while read EMAIL_ADDRESS NAME   ; do
    echo "$SCRIPT: addr=$EMAIL_ADDRESS  name=$NAME"
done
Run Code Online (Sandbox Code Playgroud)

有一个很好的资源用于这个和类似的东西:manniwood.com 的 PostgreSQL 和 bash Stuff 页面


sat*_*sat 0

你不能。您必须编写自己的函数来配对查询结果。反引号(`)将执行命令并返回输出。在您的情况下,结果将包含您的查询的输出。