日期:2014-05-16  浏览次数:20533 次

Shell执行DB2 SQL

?

#!/usr/bin/env sh

DBNODE='nodename'
DBUSER='username'
DBPASSWORD='password'


connDB2()
{
	if( db2 connect to $1  user $2 using $3 > /dev/null )
	then 
		echo 'OK'
	else
		echo "failed connect to ${DBNODE}"
		exit -1
	fi
}

releaseDB2(){
	db2 connect reset  > /dev/null
}

run(){
	connDB2 ${DBNODE} ${DBUSER} ${DBPASSWORD}
	sql="
		select 
			area_id ,areaname
		from 
			pt.area
		"
	
	db2 -x ${sql}| while read area_id areaname
	do
		echo "Result:${area_id}->${areaname}"
	done
	releaseDB2
}

echo "execute sql ................."
run

?如果有必要可以通过执行完SQL后$?的结果来判断是不是执行成功

?

?

if [ "$?" -ne "0" ]
   then echo "execute error"
   exit -1
fi 
?

下面是DB2文档中找到的返回值的含义

The return code can be one of the following:

Code ?Description

0 ? ? DB2 command or SQL statement executed successfully

1 ? ? SELECT or FETCH statement returned no rows

2 ? ? DB2 command or SQL statement warning

4 ? ? DB2 command or SQL statement error

8 ? ? Command line processor system error