其實(shí)在大多數(shù)情況下,我們并不需要從oracle存儲(chǔ)過程里返回一個(gè)或多個(gè)結(jié)果集,除非迫不得已
如果大家用過MS SQL Server或Sybase SQL Server,那么從存儲(chǔ)過程返回一個(gè)動(dòng)態(tài)的結(jié)果集是一件非常容易的事情,只要在存儲(chǔ)過程結(jié)束時(shí)寫上“select column1,column2,.... from table_list where condition“
就可以了。
但在Oracle中不能這樣做. 我們必須使用Oracle Cursor.
在Oracle PL/SQL中,Cursor用來返回一行或多行記錄,借助Cursor,我們可以從結(jié)果集中取得所有記錄.
Cursor并不難,但是要從Oracle存儲(chǔ)過程中返回結(jié)果集, 就需要用到Cursor變量,Cursor變量Oracle PL/SQL的類型是REF CURSOR, 我們只要定義了REF CURSOR 類型就可以使用Cursor變量. 比如我們可以這樣定義:
TYPE ref_cursor IS REF CURSOR;
了解了Cursor以及Cursor變量,下面就介紹如何使用Cursor變量給JDBC返回結(jié)果集.
2. 定義表結(jié)構(gòu)
在以下例子里,我們要用到一張表Hotline.
Create table hotline(country varchar2(50),pno varchar2(50));
3. 定義存儲(chǔ)過程
create or replace package PKG_HOTLINE istype HotlineCursorType is REF CURSOR;
function getHotline return HotlineCursorType;
end;
create or replace package body PKG_HOTLINE isfunction getHotline return HotlineCursorType ishotlineCursor HotlineCursorType;
beginopen hotlineCursor for select * from hotline;
return hotlineCursor;
end;
end;
在這個(gè)存儲(chǔ)過程里,我們定義了HotlineCursorType 類型,并且在存儲(chǔ)過程中簡單地查找所有的記錄并返回HotlineCursorType.
4. 測(cè)試存儲(chǔ)過程
在Oracle SQL/Plus里登陸到數(shù)據(jù)庫. 按以下輸入就看到返回的結(jié)果集.
SQL> var rs refcursor;SQL> exec :rs := PKG_HOTLINE.getHotline;SQL> print rs;
5. Java調(diào)用
簡單地寫一個(gè)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);
}}.....