What is the proper odbc command for calling Oracle stored procedure with parameters from .Net?

江枫思渺然 提交于 2019-11-29 12:55:00

I'm running .NET 3.5 and Oracle 10gR2. I've added an output parameter in response to your comment.

Server, Uid, and Pwd have been changed to protect the innocent. Set them to appropriate values.

My stored procedure:

create or replace
procedure test_proc(p1 in number, p2 in out varchar2) is
begin
  p2 := to_char(p1 + to_number(p2));
end;

My test code:

using System;
using System.Data;
using System.Data.Odbc;

class OdbcTest
{
    const string connectionString =
        @"Driver={Microsoft ODBC for Oracle};" +
        @"Server=MyTnsName;" +
        @"Uid=MySchema;" +
        @"Pwd=MyPassword;";

    public static string TryMe()
    {
        using (var odbcConn = new OdbcConnection(connectionString))
        using (var odbcCommand = odbcConn.CreateCommand())
        {
            odbcCommand.CommandText = "{ CALL test_proc(?, ?) }";
            odbcCommand.CommandType = CommandType.StoredProcedure;

            odbcCommand.Parameters.Add("p1", OdbcType.Decimal).Value = 42;
            var p2 = odbcCommand.Parameters.Add("p2", OdbcType.VarChar, 30);
            p2.Direction = ParameterDirection.InputOutput;
            p2.Value = "25";

            odbcConn.Open();
            odbcCommand.ExecuteNonQuery();

            return p2.Value as string; // returns 67
        }
    }
}

When using OUT or IN OUT parameters, the Size property of the OdbcParameter must be set to an adequate value.

In response to your comment regarding exception handling, I would have the caller of the data access method handle exceptions. With the using construct, the Dispose method will be called automatically on the command and connection objects whether there is an exception or not.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!