2015-12-21 51 views
2

我需要驗證數據庫連接是否成功/失敗。從shell腳本運行sqlplus時的錯誤處理

這是我的代碼

report=`sqlplus -S /nolog << EOF 
WHENEVER OSERROR EXIT 9; 
WHENEVER SQLERROR EXIT SQL.SQLCODE; 
connect <<username>>/<<Password>>@hostname:port 
set linesize 1500 
set trimspool on 
set verify off 
set termout off 
set echo off 
set feedback off 
set heading on 
set pagesize 0 

spool extract.csv 
<<My SQL Query>> 
spool off; 
exit; 
EOF` 

我曾嘗試基於線程Managing error handling while running sqlplus from shell scripts但其選擇第一個單元格的值,而不是連接狀態的以下選項。

if [ $report != 0 ] 
then 
echo "Connection Issue" 
echo "Error code $sql_return_code" 
exit 0;`enter code here` 
fi 

請指教。

回答

1

我需要類似的東西,但執行它有點不同。

首先,我有list.txt,其中包含我想測試的數據庫。我正在使用錢包連接,但可以編輯此密碼以保存用戶名/密碼。

LIST.TXT:

DB01 INSTANCE1.SCHEMA1 
DB02 INSTANCE2.SCHEMA2 
DB03 INSTANCE3.SCHEMA3 
DB04 INSTANCE4.SCHEMA4 

我有OK.sql其中包含我想每個數據庫上運行查詢。

OK.sql:

select 'OK' from dual; 
exit 

最後,我的用戶test.sh到LIST.TXT閱讀,嘗試連接,並在每行運行OK.sql,並記錄結果(擊鼓聲)結果。文本。

test.sh:檢查你的Result.txt

. /etc/profile 
rm result.txt 
while read -r name wallet; do 
    echo "BEGIN-"$name 
    if (sqlplus -S /@$wallet @OK.sql < /dev/null | grep -e 'OK'); then 
     echo $name "GOOD" >> result.txt 
    else 
     echo $name "BAD" >> result.txt 
    fi 
    echo "END-"$name 
done < list.txt 

運行後。

的Result.txt:

DB01 BAD 
DB02 GOOD 
DB03 GOOD 
DB04 GOOD 

我希望這有助於。