使用C#中的Odbc调用Oracle包函数

我在Oracle包中定义了一个函数:

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

如何使用Odbc从C#调用它? 我尝试了以下方法:

 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); } } } 

但我得到一个例外,说“无效的SQL语句”。
我究竟做错了什么?

在过去,我会使用类似的命令字符串:

“{?= CALL JF_TESTUSER.TESTPKG.testFunc(?)}”

有关更多信息,请参阅以下文章

尝试

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

我设法像这样调用包函数:

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

我认为您应该考虑使用Oracle Client

如果您选择ODBC只是为了创建DSN ,然后连接到它以某种方式与数据库无关,请考虑使用Enterprise Library Data Access Application Block