1、最简单的shell里调用sqlplus. sql
$ vi test1.sh #!/bin/bash sqlplus -S /nolog > result.log <<EOF set heading off feedback off pagesize 0 verify off echo off conn scotter/tigger select sysdate from dual; exit EOF $ chmod +x test1.sh $ ./test1.sh
2、把sqlplus执行结果传递给shell方法一
注意sqlplus段使用老板键`了, 赋变量的等号两侧不能有空格. shell
$ vi test2.sh #!/bin/bash #不须要> result.log或者>/dev/null VALUE=`sqlplus -S /nolog <<EOF set heading off feedback off pagesize 0 verify off echo off numwidth 4 conn scotter/tigger select count(*) from tab; exit EOF` if [ "$VALUE" -gt 0 ]; then echo "The number of rows is $VALUE." exit 0 else echo "There is no row in the table." fi $ chmod +x test2.sh $ ./test2.sh
3、把sqlplus执行结果传递给shell方法二
注意sqlplus段使用 col .. new_value .. 定义了变量并带参数exit, 而后自动赋给了shell的$?,这种状况使用比较狭窄,是对返回数字的状况专用,若是返回字符串,不是数字,退出码的方法就无能为力了。 而方法一是无论什么状况通吃的。
安全
$ vi test3.sh #!/bin/bash #用退出码返回值,须要重定向‘> result.log’,不然会显示到屏幕上。 sqlplus -S /nolog > result.log <<EOF set heading off feedback off pagesize 0 verify off echo off numwidth 4 conn scotter/tigger col coun new_value v_coun select count(*) coun from tab; exit v_coun EOF VALUE="$?" echo "The number of rows is $VALUE." $ chmod +x test3.sh $ ./test3.sh
4、把shell程序参数传递给sqlplus
$1表示第一个参数, sqlplus里能够直接使用, 赋变量的等号两侧不能有空格不能有空格. bash
$ vi test4.sh #!/bin/bash NAME="$1" sqlplus -S scotter/tigger <<EOF select * from tab where tname = upper('$NAME'); exit EOF $ chmod +x test4.sh $ ./test4.sh ttt
5、为了安全要求每次执行shell都手工输入密码 code
$ vi test5.sh #!/bin/bash echo -n "Enter password for u_test:" read PASSWD sqlplus -S /nolog <<EOF conn scotter/$PASSWD select * from tab; exit EOF $ chmod +x test5.sh $ ./test5.sh
6、为了安全从文件读取密码
对密码文件设置权限, 只有用户本身才能读写. 字符串
$ vi test6.sh #!/bin/bash PASSWD=`cat u_test.txt` sqlplus -S /nolog <<EOF conn scotrer/$PASSWD select * from tab; exit EOF $ chmod +x test6.sh $ ./test6.sh
七 、sqlplus的结果存储在文件中 it
#!/bin/sh sqlplus -S "scotter/tigger"<<EOF set heading off set feedback off set pagesize 0 set verify off set echo off spool spool_file SELECT * from teacher; spool off exit; EOF
与下列代码效果是相同的: table
#!/bin/sh sqlplus -S "scotter/tigger"<<EOF > spool_file set heading off set feedback off set pagesize 0 set verify off set echo off SELECT * from teacher; exit; EOF