How to verify sqlplus can connect?

浪子不回头ぞ 提交于 2019-12-01 03:46:01

Thanks to the reference given by @Kacper, I could adapt this sqlplus /nolog to my case; here's the idea:

  1. open sqlplus only without connecting
  2. set a specific return code on SQLERROR - this is what happens when connect fails
  3. return code can be collected as usual in the caller script:

a.sh

sqlplus /nolog << EOF
 WHENEVER SQLERROR EXIT 50
 WHENEVER OSERROR EXIT 66
 connect /@${MISTERY_DB}
 exit;
EOF

Then the call:

/ju $ export MISTERY_DB="eg_NON_EXISTING_DB"
/ju $ a.sh
SQL*Plus: Release 11.2.0.4.0 Production on Tue Nov 29 08:43:44 2016
Copyright (c) 1982, 2013, Oracle.  All rights reserved.
SQL> SQL> SQL> ERROR:
  ORA-12154: TNS:could not resolve the connect identifier specified
/ju $ echo $?
50

Also related: Connect to sqlplus in a shell script and run SQL scripts

Here is another solution you could use: WHENEVER SQLERROR sql.sqlcode works for me (on Oracle 11g):

# try a simple SELECT FROM DUAL on previously defined database in var MY_DB
sqlplus -s /@${MY_DB} << EOF
  whenever sqlerror exit sql.sqlcode;
  select 1 from dual;
  exit;
EOF
ERR_CODE=$? # then $? is loaded with error received
if [[ 0 != "${ERR_CODE}" ]] ; then
  echo could not connect :\(
else 
  echo connection succeeded
fi
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!