从shell脚本连接到oracle数据库

时间:2016-04-07 13:51:20

标签: oracle shell

我正在尝试从shell脚本连接到oracle数据库。下面给出了连接数据库的脚本:

#!/bin/bash
# Shell script to run sql files from command line.
# Pre-Req: sqlplus client shall be installed already.
###########################################################
# Variables Section (DB Details)
###########################################################
driverClassName=oracle.jdbc.driver.OracleDriver
url="(description=(address_list=(address=(protocol=TCP)(host=oradb.test.env.org)(port=1521)))(connect_data=(service_name=TEST_S)))"
DB_UserName="abc"
DB_Password="abc"
LogDirectory="/var/tmp/logs"
DataDirectory="/var/tmp/data"
DB_HostName="oradb.test.env.org"
DB_Port="1521"
DB_SID="KONTOR"
DIR_SqlFiles="C:\git\sql"
##########################################################
# All Script Functions Goes Here
##########################################################


db_statuscheck() {
  echo "`date` :Checking DB connectivity...";
  echo "`date` :Trying to connect "${DB_UserName}"/"${DB_Password}"@"${DB_SID}" ..."
  echo "exit" | sqlplus -S ${DB_UserName}/${DB_Password}@${url} | grep -q "Connected to:" > /dev/null
  if [ $? -eq 0 ]
  then
     DB_STATUS="UP"
     export DB_STATUS
     echo "`date` :Status: ${DB_STATUS}. Able to Connect..."
  else
     DB_STATUS="DOWN"
     export DB_STATUS
     echo "`date` :Status: DOWN . Not able to Connect."
     echo "`date` :Not able to connect to database with Username:  "${DB_UserName}" Password: "${DB_Password}" DB HostName: "${DB_HostName}" DB   Port: "${DB_Port}" SID: "${DB_SID}"."
     echo "`date` :Exiting Script Run..."
     exit
     fi
 }

Main() {
   echo "`date` :Starting Sql auto run script."
   db_statuscheck
   echo "`date` :Sql auto run script execution completed."
}

Main | tee autosql.log

当我尝试直接从终端连接字符串连接工作,但从shell脚本失败。我得到的输出是:

 7. apr 2016 15:18:09 :Starting Sql auto run script.
 7. apr 2016 15:18:09 :Checking DB connectivity...
 7. apr 2016 15:18:09 :Trying to connect abc/abc@TEST_S ...
 7. apr 2016 15:18:09 :Status: DOWN . Not able to Connect.
 7. apr 2016 15:18:09 :Not able to connect to database with Username: abc  abc Password: kjopsprosesser_utv4 DB HostName: oradb.test.env.orgDB Port: 1521 SID: TEST_S
 7. apr 2016 15:18:09 :Exiting Script Run...

2 个答案:

答案 0 :(得分:4)

压缩SQL * Plus中所有有趣的输出并没有帮助。但在这种情况下,你会在脚下拍摄自己。

您正在使用-s无声标记,这意味着SQL * Plus不会显示横幅,而且 - 至关重要的是 - 不会显示Connected to:消息。你的grep永远不会找到任何东西。

您可以通过在shell提示符下运行该标志来检查它;你会看到类似的东西:

$ echo "exit" | sqlplus -S abc/abc@TEST_S
$

它将返回shell提示符,没有输出。

因此,如果您删除该标记,将显示横幅和消息,您可以检查该消息。

我建议您在变量(或文件)中捕获整个输出,grep以检查连接是否成功,如果您认为问题显示输出,那么您可以看到'实际上是错的。如果你有真正的问题,你现在无法分辨出实际上是什么问题。

答案 1 :(得分:0)

ORACLE_HOME=PATH_TO_ORACLE

export ORACLE_HOME

PATH=$PATH:$ORACLE_HOME/bin

export PATH

sqlplus -s ${DBUSER}/${DBUSERPASSWORD}@//${HOST}:${PORT}/${SERVICE_NAME} <<EOF
set linesize 32767
set feedback off
set heading off

select * FROM dual;

EOF