2016-11-28 86 views
8

我想知道它是否有可能通过某种方式得到sqlplus输出来发现我的数据库是否启动。如何验证sqlplus可以连接?

我想运行一个数据库上的脚本列表,但在此之前,我想知道数据库是否启动并正在运行我的脚本。

这里是我的尝试:

sqlplus /@DB1 << EOF 
> select 1 from dual; 
> EOF 

它不能连接,但sqlplus中的返回码仍表示“一切OK”!

 
SQL*Plus: Release 11.2.0.4.0 Production on Mon Nov 28 10:06:41 2016 

Copyright (c) 1982, 2013, Oracle. All rights reserved. 

ERROR: 
ORA-12505: TNS:listener does not currently know of SID given in connect 
descriptor 


Enter user-name: SP2-0306: Invalid option. 
Usage: CONN[ECT] [{logon|/|proxy} [AS {SYSDBA|SYSOPER|SYSASM}] [edition=value]] 
where ::= [/][@] 
     ::= [][/][@] 
Enter user-name: [email protected]:/tmp/jcho $ echo $? 
0 

我知道我可以用grep我的测试查询的结果,这样的:

a.sh

sqlplus /@DB1 << EOF 
    select 'ALL_GOOD_BOY' from dual; 
EOF 

电话:

给出1行,如果连接正常工作,0否则:

$ a.sh |grep ALL_GOOD_BOY|wc -l 

...这对我来说似乎很多步骤。任何其他方式设置sqlplus在“无法连接”给出一个“错误”返回码的模式?

+1

说实话,我认为从双选择的方式是检查它的最好方法。这里是另一个线程与非常相似的主题:http://dba.stackexchange.com/questions/4718/how-check-that-the-oracle-database-is-up – Kacper

+0

这就是我害怕。如果我真的可以连接,我可以像[这里](http://stackoverflow.com/a/18111656/6019417)那样更改SQLPLUS返回码。但我不知道我能否连接。 –

+0

我不得不看更深一点,它在那里:https://stackoverflow.com/questions/2254761/sqlplus-force-it-to-return-an-error-code –

回答

6

多亏了@Kacper给出的参考,我能够适应这个sqlplus /nolog到我的情况;这里的想法:

  1. 只开放sqlplus无需连接
  2. 设置一个特定的返回码上SQLERROR - 这是当connect失败
  3. 返回代码可以收集作为主叫脚本通常会发生什么:

a.sh

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

接着,电话:

/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 

而且相关:Connect to sqlplus in a shell script and run SQL scripts

1

这里是另一个解决方案,您可以使用:WHENEVER SQLERROR sql.sqlcode作品对我来说(上的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