編程生活

             :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            113 隨筆 :: 0 文章 :: 18 評論 :: 0 Trackbacks

          其實在大多數情況下,我們并不需要從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 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;
            
            在這個存儲過程里,我們定義了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);
            }}.....

          posted on 2007-10-17 09:20 wilesun 閱讀(299) 評論(0)  編輯  收藏 所屬分類: 個人經驗
          主站蜘蛛池模板: 古交市| 金门县| 尼木县| 房产| 清新县| 佳木斯市| 富裕县| 古田县| 东明县| 新兴县| 井研县| 舟曲县| 乌什县| 湖北省| 遂川县| 永嘉县| 阜阳市| 隆尧县| 凌海市| 文成县| 疏附县| 大渡口区| 平定县| 威信县| 连州市| 乌拉特中旗| 汝州市| 调兵山市| 班玛县| 肥东县| 昭觉县| 集贤县| 珠海市| 尼木县| 和龙市| 上犹县| 昭觉县| 江川县| 遵义县| 盐亭县| 榆林市|