Call Oracle package function using Odbc from C#

五迷三道 提交于 2019-12-20 04:06:54

问题


I have a function defined inside an Oracle package:

CREATE OR REPLACE PACKAGE BODY TESTUSER.TESTPKG as
  FUNCTION testfunc(n IN NUMBER) RETURN NUMBER as
  begin
    return n + 1;
  end testfunc;
end testpkg;
/

How can I call it from C# using Odbc? I tried the following:

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

class Program {
    static void Main(string[] args) {
        using (OdbcConnection connection = new OdbcConnection("DSN=testdb;UID=testuser;PWD=testpwd")) {
            connection.Open();

            OdbcCommand command = new OdbcCommand("TESTUSER.TESTPKG.testfunc", connection);
            command.CommandType = System.Data.CommandType.StoredProcedure;

            command.Parameters.Add("ret", OdbcType.Int).Direction = ParameterDirection.ReturnValue;

            command.Parameters.Add("n", OdbcType.Int).Direction = ParameterDirection.Input;
            command.Parameters["n"].Value = 42;

            command.ExecuteNonQuery();
            Console.WriteLine(command.Parameters["ret"].Value);
        }
    }
}

But I get an exception saying "Invalid SQL Statement".
What am I doing wrong?


回答1:


In the past I would use something like to following for the command string:

"{? = CALL JF_TESTUSER.TESTPKG.testFunc(?)}"

See the following article for more information




回答2:


try

OdbcCommand command = new OdbcCommand("begin ? := TESTUSER.TESTPKG.testfunc(?) end;", connection);



回答3:


I managed to call the package function like this:

command.CommandText = @"begin
    :ret := ILMTEST.testpkg.testfunc(:n);
end;";
command.CommandType = System.Data.CommandType.Text;



回答4:


I think you should consider using the Oracle Client instead.

And if you choose ODBC to have just to create a DSN and then connect to it to be somehow database agnostic, consider using Enterprise Library Data Access Application Block.



来源:https://stackoverflow.com/questions/2949641/call-oracle-package-function-using-odbc-from-c-sharp

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