編程生活

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

          其實在大多數(shù)情況下,我們并不需要從oracle存儲過程里返回一個或多個結(jié)果集,除非迫不得已
          如果大家用過MS SQL Server或Sybase SQL Server,那么從存儲過程返回一個動態(tài)的結(jié)果集是一件非常容易的事情,只要在存儲過程結(jié)束時寫上“select column1,column2,.... from table_list where condition“
          就可以了。
          但在Oracle中不能這樣做. 我們必須使用Oracle Cursor.
          在Oracle PL/SQL中,Cursor用來返回一行或多行記錄,借助Cursor,我們可以從結(jié)果集中取得所有記錄.
          Cursor并不難,但是要從Oracle存儲過程中返回結(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. 定義存儲過程
            
            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里登陸到數(shù)據(jù)庫. 按以下輸入就看到返回的結(jié)果集.
            
            SQL> var rs refcursor;SQL> exec :rs := PKG_HOTLINE.getHotline;SQL> print rs;
          5. Java調(diào)用
            
            簡單地寫一個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 閱讀(297) 評論(0)  編輯  收藏 所屬分類: 個人經(jīng)驗
          主站蜘蛛池模板: 嘉黎县| 微博| 墨脱县| 镇原县| 淮阳县| 象州县| 青神县| 龙州县| 淮滨县| 佳木斯市| 上栗县| 沁水县| 武功县| 万全县| 芷江| 平昌县| 九台市| 惠东县| 南陵县| 四川省| 侯马市| 儋州市| 棋牌| 大丰市| 东兰县| 古浪县| 绥芬河市| 淄博市| 尉犁县| 宜兰县| 北辰区| 舟山市| 辽宁省| 定远县| 仙桃市| 宿松县| 鹤岗市| 高平市| 尚义县| 理塘县| 偃师市|