Retrieve multiple Oracle Ref Cursor using .NET data Provider for Oracle

本文介绍如何使用 ADO.NET 的 Oracle 提供程序通过存储过程获取多个结果集,并展示了如何创建存储过程及在客户端应用中填充数据集的过程。
Introduction
In my earlier article Multiple Result Sets in ADO.net using SqlClient ,we have seen how to retrieve multiple results using Sqlclient against SQL Server. This was a fairly simple and straight forward. We can achieve the same against Oracle database with a slight difference. We need to iron out couple of things before we get to nuts and bolts of it.
  • We need System.Data.OracleClient.Dll assembly that is very similar to System.Data.SqlClient.Dll,.NET Managed Provider forOracle is not a part of .NET Version 1.0, a separate download click here to download . For .NET version 1.1, it’s going to be part of the bundle. If you are new to .Net framework provider for Oracle read my articles on code101 Boost performance with .net data provider for oracle
  • We need a stored procedure to return multiple results set using REF CURSOR. For novice, A ref cursor is a PL/SQL data type that you can use in a query to fetch data. Each ref cursor query is associated with a PL/SQL function that returns a strongly typed ref cursor.
Lets get feet dirty
Create a oracle package, I assume you know what a package by the way it has two parts Specification and body
Package Specification
CREATE OR REPLACE PACKAGE PKG_MUltiResultset as

 TYPE MyRefCur is REF CURSOR;

 procedure GetReadOnlyData(EmpCur OUT MyRefCur,

			  DeptCur OUT MyRefCur,

			  SalCur OUT MyRefCur);

END;
Package body
CREATE OR REPLACE PACKAGE BODY PKG_MUltiResultset as

  PROCEDURE GetReadOnlyData(EmpCur OUT MyRefCur,

	   		   DeptCur OUT MyRefCur,

			   SalCur OUT MyRefCur)

  IS

  BEGIN 

    open EmpCur for select * from emp;

    open DeptCur for select * from dept;

    open SalCur for select * from salgrade;

  END;

 END;
Lets us get to the client part to access this stored procedure. We will establish connection to Oracle database retrieve data from three tables in one shot and fill up the dataset and bind the data to DataGrids.I am using Dataset you can try it with OracleDataReader as well.
NOTE: The Prefix is always Oracle for all the classes in Syatem.Data.OracleClient name space. Reference name spaces 
 
using System.Data.OracleClient;

using System.Data;
Private void GetData_Click(object sender, System.EventArgs e)

  {

    try

      {

	//Connect to Database

	OracleConnection oCon=new OracleConnection

        ("Data source=Firstdb;user id=scott;password=tiger");

	 oCon.Open();

	

        //Command Object

	OracleCommand oCmd =new OracleCommand

        ("PKG_MUltiResultset.GetReadOnlyData",oCon);



	//Stored Procedure

	oCmd.CommandType=CommandType.StoredProcedure;



	//Create Parameter Object

        oCmd.Parameters.Add(new OracleParameter

        ("empcur",OracleType.Cursor)).Direction=ParameterDirection.Output;

     

        oCmd.Parameters.Add(new OracleParameter

        ("DeptCur",OracleType.Cursor)).Direction=ParameterDirection.Output;

     

        oCmd.Parameters.Add(new OracleParameter

       ("SalCur",OracleType.Cursor)).Direction=ParameterDirection.Output;

	

	//Instatiate Dataset

	DataSet Ds=new DataSet();



	//Instatiate Data Adopter

	OracleDataAdapter oAdp=new OracleDataAdapter(oCmd);



	//Fill Data Set

	oAdp.Fill(Ds);



	//Bind Data to Grids

	dataGrid1.SetDataBinding(Ds,"Table");

	dataGrid2.SetDataBinding(Ds,"Table1");

	dataGrid3.SetDataBinding(Ds,"Table2");

	}

  	 catch (Exception x)

	{

	 MessageBox.Show(x.Message);

	}

      }

在使用 PL/SQL 或 JDBC(或其他数据库接口)执行 SQL 语句时,如果遇到 **“can't retrieve data for PL/SQL statement by using next”** 这类错误,通常是因为你**错误地使用了 `next()` 方法来获取结果集**,而执行的 SQL 语句**不是查询语句(SELECT)**,而是 DML(如 INSERT、UPDATE、DELETE)或 DDL(如 CREATE、ALTER)语句。 --- ### 一、原因分析 Java 中的 `ResultSet.next()` 方法只能用于**查询语句返回的结果集**(即 `SELECT` 语句)。 如果你执行的是: - `INSERT` - `UPDATE` - `DELETE` - `CREATE` - `DROP` 这些语句不会返回 `ResultSet`,因此调用 `next()` 会抛出异常或返回 false,导致你看到类似以下错误: ``` java.sql.SQLException: Operation not allowed after ResultSet is closed 或 java.lang.IllegalStateException: No data found ``` --- ### 二、示例代码对比 #### ✅ 正确使用 `next()`(用于 SELECT 查询): ```java Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT name FROM users"); while (rs.next()) { System.out.println(rs.getString("name")); } ``` #### ❌ 错误使用 `next()`(用于非查询语句): ```java Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("UPDATE users SET name='Tom' WHERE id=1"); rs.next(); // 报错:没有结果集 ``` --- ### 三、解决方法 1. **使用 `executeUpdate()` 执行 DML 语句** ```java Statement stmt = connection.createStatement(); int rowsAffected = stmt.executeUpdate("UPDATE users SET name='Tom' WHERE id=1"); System.out.println(rowsAffected + " 行被更新"); ``` 2. **使用 `execute()` 判断是否返回结果集** ```java Statement stmt = connection.createStatement(); boolean hasResultSet = stmt.execute("SELECT name FROM users"); if (hasResultSet) { ResultSet rs = stmt.getResultSet(); while (rs.next()) { System.out.println(rs.getString("name")); } } else { int rowsAffected = stmt.getUpdateCount(); System.out.println(rowsAffected + " 行受影响"); } ``` --- ### 四、总结 | SQL 类型 | 使用方法 | 是否返回 ResultSet | |----------|-----------|---------------------| | SELECT | `executeQuery()` / `execute()` | ✅ 是 | | INSERT | `executeUpdate()` / `execute()` | ❌ 否 | | UPDATE | `executeUpdate()` / `execute()` | ❌ 否 | | DELETE | `executeUpdate()` / `execute()` | ❌ 否 | | CREATE/DROP | `executeUpdate()` / `execute()` | ❌ 否 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值