|
[J2ME]Java JDBC里如何取得Oracle存储过程返回的动态结果集 作者:叶枫
版权声明:本文可以自由转载,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明 作者:叶枫(http://blog.matrix.org.cn/page/叶枫) 原文:[http://www.matrix.org.cn/resource/article/43/43999_JDBC_Oracle.html]http://www.matrix.org.cn/resource/article/43/43999_JDBC_Oracle.html[/url] 关键字:JDBC Oracle Cursor
1. 关于oracle和结果集
其实在大多数情况下,我们并不需要从oracle存储过程里返回一个或多个结果集, 除非迫不得已。
如果大家用过MS SQL Server或Sybase SQL Server,那么从存储过程返回一个 动态的结果集是一件非常容易的事情,只要在存储过程结束时写上
“select column1,column2,.... from table_list where condition“
就可以了。
但在Oracle中不能这样做. 我们必须使用Oracle Cursor. 在Oracle PL/SQL中,Cursor用来返回一行或多行记录,借助Cursor,我们可以从结果集中取得所有记录.
Cursor并不难,但是要从Oracle存储过程中返回结果集, 就需要用到Cursor变量,Cursor变量Oracle PL/SQL 的类型是REF CURSOR, 我们只要定义了REF CURSOR 类型就可以使用Cursor变量. 比如我们可以这样定义: TYPE ref_cursor IS REF CURSOR; 了解了Cursor以及Cursor变量,下面就介绍如何使用Cursor变量给JDBC返回结果集.
2. 定义表结构
在以下例子里,我们要用到一张表Hotline.
Create table hotline( country varchar2(50), pno varchar2(50));
3. 定义存储过程
create or replace package PKG_HOTLINE is
type HotlineCursorType is REF CURSOR;
function getHotline return HotlineCursorType;
end;
create or replace package body PKG_HOTLINE is function getHotline return HotlineCursorType is hotlineCursor HotlineCursorType; begin open hotlineCursor for select * from hotline; return hotlineCursor; end; end;
在这个存储过程里,我们定义了HotlineCursorType 类型,并且在存储过程中 简单地查找所有的记录并返回HotlineCursorType.
4. 测试存储过程
在Oracle SQL/Plus里登陆到数据库. 按以下输入就看到返回的结果集.
SQL> var rs refcursor; SQL> exec :rs := PKG_HOTLINE.getHotline; SQL> print rs;
5. Java调用
简单地写一个Java Class.
.... public void openCursor(){ Connection conn = null; ResultSet rs = null; CallableStatement stmt = null; String sql = “{? = call PKG_HOTLINE.getHotline()}“;
try{ conn = getConnection(); stmt = conn.prepareCall(sql); stmt.registerOutParameter(1,OracleTypes.CURSOR); stmt.execute(); rs = ((OracleCallableStatement)stmt).getCursor(1); while(rs.next()){ String country = rs.getString(1); String pno = rs.getString(2); System.out.println(“country:“+country+“|pno:”+pno); }
}catch(Exception ex){ ex.printStackTrace(); }finally{ closeConnection(conn,rs,stmt); }
} .....
好了,大功告成.
|