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