Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to verify sqlplus can connect?

I'd like to know if its possible to get sqlplus output in some way to discover if my database is up.

I want to run a list of scripts on a database, but before I do that, I want to know if the database is up and running with my script.

Here is what I tried:

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

It cannot connect, but the return code of sqlplus still says "everything 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: ju@srv:/tmp/jcho $ echo $?
0

I know I could grep the result of my test query, like that:

a.sh

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

call:

gives 1 line if connection works, 0 otherwise:

$ a.sh |grep ALL_GOOD_BOY|wc -l

... This seems many steps to me. Any other way to set sqlplus in a mode where "unable to connect" gives an "error" return code?

like image 881
J. Chomel Avatar asked Nov 28 '16 09:11

J. Chomel


People also ask

How do you check if I have SQL Plus?

Click Start > Programs > Oracle-OraHomeName > Application Development > SQL Plus. The SQL*Plus Windows GUI opens and the Log On dialog is displayed. Enter your Oracle Database username and password in the Log On dialog. If you do not know your Oracle Database username and password, ask your Database Administrator.

What is connect identifier in Sqlplus?

A connect identifier can be the connect descriptor or a name that resolves to a connect descriptor. The connect descriptor contains: Network route to the service, including the location of the listener through a protocol address. A database service name or Oracle system identifier (SID)


1 Answers

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

like image 136
J. Chomel Avatar answered Oct 24 '22 17:10

J. Chomel