編程生活

             :: 首頁 :: 新隨筆 :: 聯系 :: 聚合  :: 管理 ::
            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 閱讀(297) 評論(0)  編輯  收藏 所屬分類: 個人經驗
          主站蜘蛛池模板: 濮阳市| 油尖旺区| 读书| 塘沽区| 巴中市| 双桥区| 米泉市| 天津市| 宜都市| 定远县| 军事| 陇西县| 永胜县| 从化市| 睢宁县| 托里县| 太湖县| 宜兰县| 垦利县| 武邑县| 新野县| 乡宁县| 民县| 西乌| 正镶白旗| 中山市| 江达县| 巴林左旗| 固镇县| 浦县| 南岸区| 洪雅县| 扎囊县| 涟源市| 梓潼县| 绥化市| 左权县| 新营市| 宜都市| 绥棱县| 吉隆县|