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)
我成功地使用了
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 页面
| 归档时间: |
|
| 查看次数: |
11263 次 |
| 最近记录: |