摘自:http://www.c-sharpcorner.com/UploadFile/john_charles/CallingOraclestoredproceduresfromMicrosoftdotNET06222007142805PM/CallingOraclestoredproceduresfromMicrosoftdotNET.aspx
Introduction

This article is intended to illustrate how to illustrate how to call Oracle stored procedures and functions from Microsoft.NET through the Microsoft.NET Oracle provider and its object model residing in the namespace System.Data.OracleClient. I will cover several possible scenarios with advanced examples.

Executing a stored procedure

Let's begin with definitions. A procedure is a module that performs one or more actions. A function is a module that returns a value and unlike procedures a call to a function can exist only as part of an executable such as an element in an expression or the value assigned as default in a declaration of a variable.

The first example illustrates how to call an Oracle procedure passing input parameters and retrieving value by output parameters. For all the examples, we're going to use the default database ORCL which comes with the Oracle database installation. The following code in Listing 1 shows how to create a procedure named count_emp_by_dept which receives as its input parameter the department number and sends as its output parameter the number of employees in this department.

create or replace procedure count_emp_by_dept(pin_deptno number, pout_count out number)
is
begin
 select count(*) into pout_count
 from scott.emp
 where deptno=pin_deptno;
end count_emp_by_dept;

Listing 1: Creating the procedure  count_emp_by_dept.

Now let's create a console application and add a reference to the assembly System.Data.OracleClient.dll to your project.

The code for this example is illustrated in Listing 2. The first thing to do is to import the object's class residing in the namespace System.Data.OracleClient with the using directive. Then you must set up the parameters and finally call the procedure using ExecuteNonQuery method of the OracleCommand object.

Using System;

using System.Collections.Generic;

using System.Text;

using System.Data.OracleClient;

using System.Data;

namespace CallingOracleStoredProc

{

class Program

{

static void Main(string[] args)

{

using (OracleConnection objConn = new OracleConnection("Data Source=ORCL; User ID=scott; Password=tiger"))

{

OracleCommand objCmd = new OracleCommand();

objCmd.Connection = objConn;

objCmd.CommandText = "count_emp_by_dept";

objCmd.CommandType = CommandType.StoredProcedure;

objCmd.Parameters.Add("pin_deptno", OracleType.Number).Value = 20;

objCmd.Parameters.Add("pout_count", OracleType.Number).Direction = ParameterDirection.Output;

try

{

objConn.Open();

objCmd.ExecuteNonQuery();

System.Console.WriteLine("Number of employees in department 20 is {0}", objCmd.Parameters["pout_count"].Value);

}

catch (Exception ex)

{

System.Console.WriteLine("Exception: {0}",ex.ToString());

}

objConn.Close();

}

}

}

}

Listing 2: The application code calling the stored procedure.

Executing a function

As function is similar to procedures except they return a value, we need to set up a return parameter. Let's see the example.

The following code in Listing 3 shows how to create a function named get_count_emp_by_dept which receives as its input parameter the department number and returns the number of employees in this department. It's very similar to the former procedure in the previous section.

create or replace function get_count_emp_by_dept(pin_deptno number)
 return number
is
 var_count number;
begin
 select count(*) into var_count
 from scott.emp
 where deptno=pin_deptno;
 return var_count;
end get_count_emp_by_dept;

Listing 3: Creating an Oracle function.

Now let's see in the Listing 4 the application code which calls the function. As you can see, we need to define a return parameter to get the returned value. The other part of the code is similar for calling a procedure.

using System;

using System.Collections.Generic;

using System.Text;

using System.Data.OracleClient;

using System.Data;

namespace CallingOracleStoredProc

{

class Program

{

static void Main(string[] args)

{

using (OracleConnection objConn = new OracleConnection("Data Source=ORCL; User ID=scott; Password=tiger"))

{

OracleCommand objCmd = new OracleCommand();

objCmd.Connection = objConn;

objCmd.CommandText = "get_count_emp_by_dept";

objCmd.CommandType = CommandType.StoredProcedure;

objCmd.Parameters.Add("pin_deptno", OracleType.Number).Value = 20;

objCmd.Parameters.Add("return_value", OracleType.Number).Direction = ParameterDirection.ReturnValue;

try

{

objConn.Open();

objCmd.ExecuteNonQuery();

System.Console.WriteLine("Number of employees in department 20 is {0}", objCmd.Parameters["return_value"].Value);

}

catch (Exception ex)

{

System.Console.WriteLine("Exception: {0}",ex.ToString());

}

objConn.Close();

}

}

}

}

Listing 4: The application code calling the function.

Working with cursors

You can use the REF CURSOR data type to work with Oracle result set. To retrieve the result set, you must define a REF CURSOR output parameter in a procedure or a function to pass the cursor back to your application.

Now we're going to define a procedure which opens and sends a cursor variable to our application.

Let's define the package and procedure header as shown in Listing 5.

create or replace package human_resources
as
 type t_cursor is ref cursor;
 procedure get_employee(cur_employees out t_cursor);
end human_resources;

Listing 5: Creation of the package human_resources and the procedure get_employee.

And now the package definition as shown in Listing 6.

create or replace package body human_resources
as
 procedure get_employee(cur_employees out t_cursor)
 is
 begin
  open cur_employees for select * from emp;
 end get_employee;
end human_resources;

Listing 6. The creation of the package body.

Now let's see in Listing 7 the application code calling the procedure inside the package. See the name syntax for calling the procedure contained within a package [package_name].[procedure_name]. In order to get a cursor, you need to define a cursor parameter with the ParameterDirection set up to Output and finally call the ExecuteReader method in the OracleCommand instance.

Using System;

using System.Collections.Generic;

using System.Text;

using System.Data.OracleClient;

using System.Data;

namespace CallingOracleStoredProc

{

class Program

{

private static void prvPrintReader(OracleDataReader objReader)

{

for (int i = 0; i < objReader.FieldCount; i++)

{

System.Console.Write("{0}\t",objReader.GetName(i));

}

System.Console.Write("\n");

while (objReader.Read())

{

for (int i = 0; i < objReader.FieldCount; i++)

{

System.Console.Write("{0}\t", objReader[i].ToString());

}

System.Console.Write("\n");

}

}

static void Main(string[] args)

{

using (OracleConnection objConn = new OracleConnection("Data Source=ORCL; User ID=scott; Password=tiger"))

{

OracleCommand objCmd = new OracleCommand();

objCmd.Connection = objConn;

objCmd.CommandText = "human_resources.get_employee";

objCmd.CommandType = CommandType.StoredProcedure;

objCmd.Parameters.Add("cur_employees", OracleType.Cursor).Direction = ParameterDirection.Output;

try

{

objConn.Open();

OracleDataReader objReader = objCmd.ExecuteReader();

prvPrintReader(objReader);

}

catch (Exception ex)

{

System.Console.WriteLine("Exception: {0}",ex.ToString());

}

objConn.Close();

}

}

}

}

Listing 7: The application code.

If the procedure returns more than one cursor, the DataReader object accesses them by calling the NextResult method to advance the next cursor.

Let's see the following example.

Listing 8 shows how to create the package header.

create or replace package human_resources
as
 type t_cursor is ref cursor;
 procedure get_employee_department(cur_employees out t_cursor, cur_departments out t_cursor);
end human_resources;

Listing 8: Package reader.

The package body is shown in Listing 9.

create or replace package body human_resources
as
 procedure get_employee_department(cur_employees out t_cursor, cur_departments out t_cursor)
 is
 begin
  open cur_employees for select * from emp;
  open cur_departments for select * from dept;
 end get_employee_department;
end human_resources;

Listing 9: Creation of the package body.

Let's see the application code in Listing 10.

using System;

using System.Collections.Generic;

using System.Text;

using System.Data.OracleClient;

using System.Data;

namespace CallingOracleStoredProc

{

class Program

{

private static void prvPrintReader(OracleDataReader objReader)

{

for (int i = 0; i < objReader.FieldCount; i++)

{

System.Console.Write("{0}\t",objReader.GetName(i));

}

System.Console.Write("\n");

while (objReader.Read())

{

for (int i = 0; i < objReader.FieldCount; i++)

{

System.Console.Write("{0}\t", objReader[i].ToString());

}

System.Console.Write("\n");

}

}

static void Main(string[] args)

{

using (OracleConnection objConn = new OracleConnection("Data Source=ORCL; User ID=scott; Password=tiger"))

{

OracleCommand objCmd = new OracleCommand();

objCmd.Connection = objConn;

objCmd.CommandText = "human_resources.get_employee_department";

objCmd.CommandType = CommandType.StoredProcedure;

objCmd.Parameters.Add("cur_employees", OracleType.Cursor).Direction = ParameterDirection.Output;

objCmd.Parameters.Add("cur_departments", OracleType.Cursor).Direction = ParameterDirection.Output;

try

{

objConn.Open();

OracleDataReader objReader = objCmd.ExecuteReader();

prvPrintReader(objReader);

objReader.NextResult();

prvPrintReader(objReader);

}

catch (Exception ex)

{

System.Console.WriteLine("Exception: {0}",ex.ToString());

}

objConn.Close();

}

}

}

}

Listing 10: The application code.

Working with DataSet and DataAdapter

The final example shows how to fill and update a DataSet object through a DataAdapter object.

The first thing to do is create four CRUD procedure to the emp table.  Listing 11 shows how to create the package header.

create or replace package human_resources
as
 type t_cursor is ref cursor;
 procedure select_employee(cur_employees out t_cursor);
 procedure insert_employee(p_empno number, p_ename varchar2, p_job varchar2, p_mgr number, p_hiredate date, p_sal number, p_comm number, p_deptno number);
 procedure update_employee(p_empno number, p_ename varchar2, p_job varchar2, p_mgr number, p_hiredate date, p_sal number, p_comm number, p_deptno number);
 procedure delete_employee(p_empno number);
end human_resources;

Listing 11: The creation of the package header.

Now let's define the package body as shown in Listing 12

create or replace package body human_resources
as
 procedure select_employee(cur_employees out t_cursor)
 is
 begin
   open cur_employees for select empno, ename, job, mgr, hiredate, sal, comm, deptno from emp;
 end select_employee;
 procedure insert_employee(p_empno number, p_ename varchar2, p_job varchar2, p_mgr number, p_hiredate date, p_sal number, p_comm number, p_deptno number)
 is
 begin
   update emp
   set ename=p_ename, job=p_job, mgr=p_mgr, hiredate=p_hiredate, sal=p_sal, comm=p_comm, deptno=p_deptno
   where empno=p_empno;
 end insert_employee;
 procedure update_employee(p_empno number, p_ename varchar2, p_job varchar2, p_mgr number, p_hiredate date, p_sal number, p_comm number, p_deptno number)
 is
 begin
   insert into emp
   values(p_empno,p_ename,p_job,p_mgr,p_hiredate,p_sal,p_comm,p_deptno);
 end update_employee;
 procedure delete_employee(p_empno number)
 is
 begin
    delete from emp
    where empno=p_empno;
 end delete_employee;
end human_resources;

Listing 12: The package body creation.

And finally, let's see the application code in Listing 13. As you can see, to fill the data table, we need to define the CRUD (create, read, update, delete) operations through the OracleCommand and associate it to the DataAdapter. I fill the data table, and print out a message with the number of employees so far, and then add a new row representing one employee entity.

using System;

using System.Collections.Generic;

using System.Text;

using System.Data.OracleClient;

using System.Data;

namespace CallingOracleStoredProc

{

class Program

{

static void Main(string[] args)

{

using (OracleConnection objConn = new OracleConnection("Data Source=ORCL; User ID=scott; Password=tiger"))

{

OracleDataAdapter objAdapter = new OracleDataAdapter();

OracleCommand objSelectCmd = new OracleCommand();

objSelectCmd.Connection = objConn;

objSelectCmd.CommandText = "human_resources.select_employee";

objSelectCmd.CommandType = CommandType.StoredProcedure;

objSelectCmd.Parameters.Add("cur_employees", OracleType.Cursor).Direction = ParameterDirection.Output;

objAdapter.SelectCommand = objSelectCmd;

OracleCommand objInsertCmd = new OracleCommand();

objInsertCmd.Connection = objConn;

objInsertCmd.CommandText = "human_resources.insert_employee";

objInsertCmd.CommandType = CommandType.StoredProcedure;

objInsertCmd.Parameters.Add("p_empno", OracleType.Number, 4, "empno");

objInsertCmd.Parameters.Add("p_ename", OracleType.VarChar, 10, "ename");

objInsertCmd.Parameters.Add("p_job", OracleType.VarChar, 9, "job");

objInsertCmd.Parameters.Add("p_mgr", OracleType.Number, 4, "mgr");

objInsertCmd.Parameters.Add("p_hiredate", OracleType.DateTime,12, "hiredate");

objInsertCmd.Parameters.Add("p_sal", OracleType.Number, 7, "sal");

objInsertCmd.Parameters.Add("p_comm", OracleType.Number, 7, "comm");

objInsertCmd.Parameters.Add("p_deptno", OracleType.Number, 7, "deptno");

objAdapter.InsertCommand = objInsertCmd;

OracleCommand objUpdateCmd = new OracleCommand();

objUpdateCmd.Connection = objConn;

objUpdateCmd.CommandText = "human_resources.update_employee";

objUpdateCmd.CommandType = CommandType.StoredProcedure;

objUpdateCmd.Parameters.Add("p_empno", OracleType.Number, 4, "empno");

objUpdateCmd.Parameters.Add("p_ename", OracleType.VarChar, 10, "ename");

objUpdateCmd.Parameters.Add("p_job", OracleType.VarChar, 9, "job");

objUpdateCmd.Parameters.Add("p_mgr", OracleType.Number, 4, "mgr");

objUpdateCmd.Parameters.Add("p_hiredate", OracleType.DateTime, 10, "hiredate");

objUpdateCmd.Parameters.Add("p_sal", OracleType.Number, 7, "sal");

objUpdateCmd.Parameters.Add("p_comm", OracleType.Number, 7, "comm");

objUpdateCmd.Parameters.Add("p_deptno", OracleType.Number, 7, "deptno");

objAdapter.UpdateCommand = objUpdateCmd;

OracleCommand objDeleteCmd = new OracleCommand();

objDeleteCmd.Connection = objConn;

objDeleteCmd.CommandText = "human_resources.delete_employee";

objDeleteCmd.CommandType = CommandType.StoredProcedure;

objDeleteCmd.Parameters.Add("p_empno", OracleType.Number, 4, "empno");

objAdapter.DeleteCommand = objDeleteCmd;

try

{

DataTable dtEmp = new DataTable();

objAdapter.Fill(dtEmp);

System.Console.WriteLine("Employee count = {0}", dtEmp.Rows.Count );

dtEmp.Rows.Add(7935, "John", "Manager", 7782, DateTime.Now,1300,0,10);

objAdapter.Update(dtEmp);

}

catch (Exception ex)

{

System.Console.WriteLine("Exception: {0}",ex.ToString());

}

objConn.Close();

}

}

}

}

Listing 12: The application code.

转载于:https://www.cnblogs.com/NRabbit/archive/2009/07/10/1736182.html

Calling Oracle stored procedures from Microsoft.NET相关推荐

  1. Spring, Hibernate and Oracle Stored Procedures

    一篇英文博文,写的是利用hibernate处理存储过程中的游标等等: Motivation: While there are a few resources available online for ...

  2. 把Oracle数据库移植到Microsoft SQL Server 7 0

    分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow 也欢迎大家转载本篇文章.分享知识,造福人民,实现我们中华民族伟大复兴! 把Ora ...

  3. 自动备份SQL Server数据库中用户创建的Stored Procedures

    为了避免意外丢失/损坏辛苦创建的Stored Procedures,或者想恢复到以前版本的Stored Procedures,这样提供了一个有效方法,可以自动将指定数据库中的Stored Proced ...

  4. sql oraoledb.oracle,无法创建链接服务器XXXXX的 OLE DB 访问接口OraOLEDB.Oracle的实例。 (Microsoft SQL Server,错误7302)...

    无法创建链接服务器"XXXXX"的 OLE DB 访问接口"OraOLEDB.Oracle"的实例. (Microsoft SQL Server,错误: 730 ...

  5. oracle ole db 安装,Microsoft OLE DB Provider for Oracle(数据库引擎)

    Microsoft OLE DB Provider for Oracle(数据库引擎) 06/15/2011 本文内容 Microsoft OLE DB Provider for Oracle 允许对 ...

  6. SQL Server :Stored procedures存储过程初级篇

    对于SQL Server,我是个拿来主义.很多底层的原理并不了解,就直接模仿拿着来用了,到了报错的时候,才去找原因进而逐步深入底层.我想,是每一次的报错,逼着我一点点进步的吧. 近期由于项目的原因,我 ...

  7. mysql stored procedures with return values

    存储过程的功能非常强大,在某种程度上甚至可以替代业务逻辑层, 接下来就一个小例子来说明,用存储过程插入或更新语句. 1.数据库表结构 所用数据库为Sql Server2008. 2.创建存储过程 (1 ...

  8. The return types for the following stored procedures could not be detected

    1.使用dbml映射数据库,添加存储过程到dbml文件时报错. 2.原因:存储过程中使用了临时表 3.解决方案 3.1 通过自定义表值变量实现 Ex: DECLARE @TempTable TABLE ...

  9. 查看Oracle的procedures,Oracle通过shell脚本查看procedure的信息

    在一个schema中,可能含有大量的procedure, 有时候想查看具体的信息,一般得通过toad,plsql dev等工具来查看,有时候在尽可能摆脱图形工具的前提下,想能够尽快的查找一些信息,还是 ...

最新文章

  1. 释放内存触发断点及数组、指针的NULL初始化
  2. [BZOJ3631][JLOI2014]松鼠的新家
  3. Stella Forum v2 线上版开发总结
  4. python读txt文件 数组-python将txt等文件中的数据读为numpy数组的方法
  5. 《leetcode》first-missing-positive
  6. abaqus实例_使用Python在ABAQUS中创建XYData数据
  7. java in think 多态问题
  8. 冲刺二阶段-个人总结04
  9. 使用MySQL管理工具-SQLyog9.63报错号码2003,超详细解析
  10. React Native可视化开发工具
  11. 计算机win7如何连接wifi网络,细说win7怎么共享wifi
  12. 开源 java CMS - FreeCMS2.8 移动app站点配置
  13. Jekyll分页功能
  14. 水面倒影风格的LOGO在线做
  15. 让用户输入一个三位数(若不是三位数则提示错误),判断该数是否是水仙花数。(水仙花数:每一位上的数字的立方和,等于该数本身)
  16. Java pcm文件与wav文件互转
  17. 【视频课】行为识别课程更新!CNN+LSTM理论与实践!
  18. 某互联网银行 区块链技术暑假实习生在线笔试 回忆
  19. 吐血整理:42个人工智能机器学习数据集推荐
  20. 苹果cms V10模板主题|白色简约风格自适应模板下载

热门文章

  1. 使用myeclipse的第一步
  2. 2022-2028年中国新型氟塑料行业市场发展模式及投资机会预测报告
  3. 2022-2028年中国丁基橡胶行业市场深度分析及投资前景展望报告
  4. 【JavaScript总结】JavaScript语法基础:BOM
  5. Centos7安装Nginx详细步骤
  6. TVM代码生成codegen
  7. 对端边缘云网络计算模式:透明计算、移动边缘计算、雾计算和Cloudlet
  8. MindInsight计算图可视设计
  9. Python的输出:Python2.7和Python3.7的区别
  10. Ubuntu 系统自带的截图工具screenshot