2012-03-20 68 views
1

我试图从C#(.NET 3.5)通过ODBC连接调用本地SQL Server(2008 R2)实例上的存储过程。我遇到的问题是存储的proc似乎没有收到输入参数。ODBC命令不接受参数

我也设置了分析器 - 没有看到任何输入参数使其到数据库。

发生了什么! :(

PS - 请不要建议使用任何不同的技术


的App.config

<?xml version="1.0" encoding="utf-8" ?> 
<configuration> 
    <connectionStrings> 
    <add name="MYDB" connectionString="Driver={SQL Server};Server=localhost;Database=MYDB;Uid=user_name;Pwd=password;"/> 
    </connectionStrings> 
</configuration> 

的Program.cs

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

namespace DatabaseTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      string mssqlConnectionString = ConfigurationManager.ConnectionStrings["MYDB"].ConnectionString; 

      using (OdbcConnection connection = new OdbcConnection(mssqlConnectionString)) 
      { 
       connection.Open(); 

       using (OdbcCommand command = new OdbcCommand("usp_Get_UserInfo", connection)) 
       { 
        command.CommandType = CommandType.StoredProcedure; 
        command.CommandTimeout = 0; 
        command.Parameters.Add(new OdbcParameter("@username", OdbcType.VarChar, 32) { Value = "Bob", IsNullable = true, }); 

        using (OdbcDataReader reader = command.ExecuteReader()) 
        { 
         while (reader.Read()) 
         { 
          string userName = reader["USER_NAME"].ToString(); 
          string userInfo = reader["USER_INFO"].ToString(); 

          Console.WriteLine(String.Format("{0} | {1}", 
           userName, userInfo)); 
         } 

         reader.Close(); 
        } 
       } 

       connection.Close(); 
      } 
     } 
    } 
} 

存储过程

USE [MYDB] 
GO 

SET ANSI_NULLS ON 
GO 
SET QUOTED_IDENTIFIER ON 
GO 

ALTER PROCEDURE [dbo].[usp_Get_UserInfo] 
    @username varchar(32) = null 
AS 
BEGIN 

    SET NOCOUNT ON; 

    SELECT u.[USER_NAME] 
     , u.USER_INFO 
    FROM dbo.UserDataTable u 
     WHERE u.[USER_NAME] = ISNULL(@username, u.[USER_NAME) 

END 

结果

[USER_NAME] | [USER_INFO] 
Alice | Alice's info 
Bob | Bob's info 
Charlie | Charlie's info 
+0

你会想要删除'.Open()'和'.Close()'你有,'使用'将处理打开和关闭。 – CAbbott 2012-03-20 14:58:43

+0

@CAbbott是的,太好了。这是问题所在。它现在的作品... – 2012-03-20 14:59:40

+0

对不起,我忘了关闭讽刺块。我的错。 – 2012-03-20 15:05:19

回答

1

发现了一些激烈的谷歌搜索后的答案。

Execute Parameterized SQL StoredProcedure via ODBC

看来,ODBC连接需要存储过程中一个非常有趣的方式来调用。

我没有得到相同的错误,因为我的存储过程有一个可为空的参数。因此,我没有得到任何错误。

using (OdbcCommand command = new OdbcCommand("{call usp_Get_UserInfo (?)}", connection))