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
你会想要删除'.Open()'和'.Close()'你有,'使用'将处理打开和关闭。 – CAbbott 2012-03-20 14:58:43
@CAbbott是的,太好了。这是问题所在。它现在的作品... – 2012-03-20 14:59:40
对不起,我忘了关闭讽刺块。我的错。 – 2012-03-20 15:05:19