2012-01-17 950 views
1

我有一个shell脚本,它将连接到数据库并获取结果。我的剧本就像是在shell脚本中捕获db2 sql结果

#!/bin/bash 
getResults() 
{ 
    db2 "connect to ${1} user ${2} using ${3}" 
    db2 "set schema ${4}" 
    status=`db2 -x "select status from results where id=1"` 
    echo $status 
} 
#MAIN STARS HERE 
getResults dbname foo bar test 

现在我想用

select status,timestamp from results where id=1 

如何运行上面的查询,以获得从结果表的多个列,并使用单个查询同时捕获状态和时间戳到两个不同的shell变量而不是运行2个不同的充查询,如

#!/bin/bash 
getResults() 
{ 
    db2 "connect to ${1} user ${2} using ${3}" 
    db2 "set schema ${4}" 
    status=`db2 -x "select status from results where id=1"` 
    echo $status 
    timestamp=`db2 -x "select timestamp from results where id=1"` 
    echo $timestamp 

} 
#MAIN STARS HERE 
getResults dbname foo bar test 

我的成绩表是这样的:

create table (id number, status char(1), timestamp datetime); 

和数据是提前就像

1 P <some ts> 
2 F <some ts> 

谢谢!

+0

表格在哪里?如果它在数据库中,则应该能够将其作为常规插入/创建语句运行......对于shell脚本无法提供帮助,对不起。 – 2012-01-17 22:07:40

+0

我的表在数据库中,我想从我的shell脚本使用上述查询来检索该表中的数据。我知道如何从db2 cnsole运行sql。 – springpress 2012-01-17 23:06:55

回答

2

问题是您在getResults函数中创建的数据库连接对于子shell不可见(即,当您调用db2 -x时)。使用反引号调用一个新的shell。

为了使这项工作,你必须保持你的查询在相同的外壳:

db2 "connect to ${1} user ${2} using ${3}" 
db2 "set schema ${4}" 

db2 -x "select status,timestamp from results where id = 1" | while read status timestamp ; do 
    echo $status 
    echo $timestamp 
done 

注意与while循环在这里您可以输出多行如果查询返回超过1行。修改SQL仅返回1行很容易。

+0

看起来像它会解决我的问题。让我明天测试一下并回复你。感谢您的回答。 – springpress 2012-01-18 03:34:23

+0

它的工作表示感谢! – springpress 2012-01-18 15:06:30