Java調用Oracle預存程序返回多條結果集

來源:互聯網
上載者:User

Java調用Oracle預存程序返回多條結果集

Oracle版本:11g

Oracle預存程序,使用遊標的方式返回多行、多列資料集合:

CREATE OR REPLACE PROCEDURE SP_DATA_TEST( /*P_ID  IN INT,*/ --傳入參數,不需要可注釋
                                        O_CUR OUT SYS_REFCURSOR --輸出資料,本文重點描述
                                        ) IS
BEGIN
  OPEN O_CUR FOR
    SELECT *
      FROM (SELECT 'A', SYSDATE - 1
              FROM DUAL
            UNION ALL
            SELECT 'B', SYSDATE
              FROM DUAL
            UNION ALL
            SELECT 'C', SYSDATE + 1 FROM DUAL) O
    WHERE 1 = 1;
END;

Java代碼編碼,程式直接調用Oracle的預存程序:SP_DATA_TEST,調用的方法:call SP_DATA_TEST(?),本文只需要輸出資料,不需要輸入參數,故只需要一個“?”即可,若是需要傳輸參數,則根據需要填寫多個參數即可。本文直接使用了main方法測試,也可先自建Java Oracle串連池後使用。

package com.***.test;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ProceTest {

    public static void main(String[] args) {
        try {
            DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
            Class.forName("oracle.jdbc.driver.OracleDriver");
            String url = "jdbc:oracle:thin:@10.0.0.1:1521:dbcsk";
            String username = "****";
            String password = "***";
            Connection conn = DriverManager.getConnection(url, username,
                    password);
            String sql = "{call SP_DATA_TEST(?)}";
            CallableStatement statement = conn.prepareCall(sql);
//            statement.setInt(1, 1);
           
            statement.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR);
            statement.execute();
           
            ResultSet rs = (ResultSet)statement.getObject(1);
            int i=1;
            while (rs.next()) {
                System.out.println(rs.getString(1)+":"+rs.getString(2));
                i++;
            }
            rs.close();
            statement.close();
            conn.close();
           
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

}

程式傳回值:

A:2016-04-29 11:12:52
B:2016-03-23 11:12:52
C:2016-03-24 11:12:52

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.