从 C# 使用 Odbc 调用 Oracle 包函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2949641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 20:43:46  来源:igfitidea点击:

Call Oracle package function using Odbc from C#

c#oracleodbc

提问by Paolo Tedesco

I have a function defined inside an Oracle package:

我在 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;
/

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

如何使用 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);
        }
    }
}

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

但是我收到一个异常,说“无效的 SQL 语句”。
我究竟做错了什么?

回答by Garett

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

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

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

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

See the following articlefor more information

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

回答by Erich Kitzmueller

try

尝试

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

回答by Paolo Tedesco

I managed to call the package function like this:

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

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

回答by Will Marcouiller

I think you should consider using the Oracle Clientinstead.

我认为你应该考虑使用Oracle Client代替。

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

如果您选择 ODBC 只需要创建一个DSN然后连接到它以某种方式与数据库无关,请考虑使用.Enterprise LibraryData Access Application Block