gpt4 book ai didi

c# - ExecutenonQuery 不工作

转载 作者:太空狗 更新时间:2023-10-30 00:05:20 24 4
gpt4 key购买 nike

我存储的过程如下:

ALTER PROC pr_Update_Users_Nomination
(
@UserID AS VARCHAR(100),
@Nominated AS BIT
)
AS

UPDATE User
SET isNominated = @Nominated
WHERE
EMPID = @UserID;

我想从 C# 代码调用这个过程:下面是我正在尝试的代码:

void OpenConnection()
{
string Nominated = "False";
//Connection String
string sConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString;
SqlConnection mySqlCon = new SqlConnection(sConnString);
SqlCommand mySqlCom = mySqlCon.CreateCommand();

//Call the stored proc and provide in parameters
mySqlCom.CommandText = "EXECUTE pr_Update @UserID @Nominated";
mySqlCom.Parameters.Add("@UserID", SqlDbType.VarChar, 20).Value = UserID;
mySqlCom.Parameters.Add("@Nominated", SqlDbType.Bit).Value = Nominated;

mySqlCon.Open();
mySqlCom.ExecuteNonQuery();
mySqlCon.Close();
}

我得到一个错误提示

Incorrect Syntax near @Nominated

最佳答案

首先,在执行带有参数(s)的过程时,用逗号分隔参数

EXECUTE pr_Update @UserID, @Nominated

其次,将你的代码修改成这样,

    string sConnString = System.Configuration.ConfigurationManager.ConnectionStrings["ConString1"].ConnectionString;
using(SqlConnection mySqlCon = new SqlConnection(sConnString))
{
using(SqlCommand mySqlCom = new SqlCommand())
{
mySqlCom.Connection = mySqlCon;
mySqlCom.CommandText = "pr_Update";
mySqlCom.CommandType = CommandType.StoredProcedure;
mySqlCom.Parameters.Add("@UserID", SqlDbType.VarChar, 20).Value = UserID;
mySqlCom.Parameters.Add("@Nominated", SqlDbType.Bit).Value = Nominated;
try
{
mySqlCon.Open();
mySqlCom.ExecuteNonQuery();
}
catch(SqlException ex)
{
// do something with the exception
// don't hide it
}

}
}

关于c# - ExecutenonQuery 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13381318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com