1. 關於Oracle和結果集其實在大多數情況下,我們並不需要從Oracle存儲過程裡返回一個或多個結果集,
除非迫不得已。在此僅對Oracle的調用存儲過程返回集 進行處理。
2種數據連接池(jdbc ,c3p0)
2. 定義表結構在以下例子裡,我們要用到一張表Hotline.
Create table hotline(
country varchar2(50),
pno varchar2(50));
3. 定義存儲過程
create or replace package PKG_HOTLINE istype 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();
//如果是c3p0的數據連接池
//下方應改為(rs = (ResultSet) cstmt.getObject(1);)
//否則會報異常
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);
}}
.....