2012-01-17 945 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