java调用oracle存储过程返回多条结果集

时间:2022-12-08 04:28:27

原创+整理,不喜勿喷!

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连接池后使用。

 1 package com.***.test;
 2 
 3 import java.sql.CallableStatement; 4 import java.sql.Connection; 5 import java.sql.DriverManager; 6 import java.sql.ResultSet; 7 import java.sql.SQLException; 8 9 public class ProceTest { 10 11 public static void main(String[] args) { 12 try { 13 DriverManager.registerDriver(new oracle.jdbc.OracleDriver()); 14 Class.forName("oracle.jdbc.driver.OracleDriver"); 15 String url = "jdbc:oracle:thin:@10.0.0.1:1521:dbcsk"; 16 String username = "****"; 17 String password = "***"; 18 Connection conn = DriverManager.getConnection(url, username, 19  password); 20 String sql = "{call SP_DATA_TEST(?)}"; 21 CallableStatement statement = conn.prepareCall(sql); 22 // statement.setInt(1, 1); 23 24 statement.registerOutParameter(1, oracle.jdbc.OracleTypes.CURSOR); 25  statement.execute(); 26 27 ResultSet rs = (ResultSet)statement.getObject(1); 28 int i=1; 29 while (rs.next()) { 30 System.out.println(rs.getString(1)+":"+rs.getString(2)); 31 i++; 32  } 33  rs.close(); 34  statement.close(); 35  conn.close(); 36 37 } catch (SQLException e) { 38  e.printStackTrace(); 39 } catch (ClassNotFoundException e) { 40  e.printStackTrace(); 41  } 42  } 43 44 }

 程序返回值:

A:2016-03-22 14:46:52
B:2016-03-23 14:46:52
C:2016-03-24 14:46:52