【问题标题】:How to Pass Variables to SqlCommand如何将变量传递给 SqlCommand
【发布时间】:2012-04-20 01:35:48
【问题描述】:

我已经彻底搜索,但找不到将我的列数据SET 到我使用 SQL UPDATE 语句初始化的变量的方法。

这是导致问题的一段代码:

int maxId;
SqlConnection dataConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString) ;
SqlCommand dataCommand = new SqlCommand("select max(UserID) from Registration", dataConnection) ;
dataConnection.Open();
maxId = Convert.ToInt32(dataCommand.ExecuteScalar());
string Id = maxId.ToString();

// this next line is not working
SqlCommand _setvin = new SqlCommand("UPDATE Registration SET VIN=maxId , Voted=0  WHERE UserID=maxId", dataConnection);
_setvin.ExecuteNonQuery();

dataConnection.Close();

请指导我如何更正上面的注释行。

【问题讨论】:

    标签: sql sql-server c#-4.0 ado.net sqlcommand


    【解决方案1】:

    我认为您正在尝试这样做:

    var _setvin = new SqlCommand("UPDATE Registration SET VIN = @maxId, Voted = 0 WHERE UserID = @maxId", dataConnection);
    _setvin.Parameters.AddWithValue("@maxId", maxId);
    _setvin.ExecuteNonQuery();
    

    您需要首先更改您的 SQL 语句以包含maxId 的参数;我在你的 SQL 中调用 @maxId。然后,您需要为该命令提供该参数的值。这是通过Parameters.AddWithValue() 方法完成的。

    【讨论】:

    • 用你的解决方案给出错误“无效的列名”.. 请注意 maxId 是变量名而不是列名... **我想设置名称为 VIN 且值包含在 maxId 中的列 **
    • @Sana 我使用@maxId 作为变量,而不是列。这里涉及的列是VINVotedUserID
    • 这里不起作用..." u jx 给出的解决方案捕获了无效的列名 'maxId' 异常
    • @Sana 那么你没有正确复制我的代码,因为我没有对maxId 进行任何引用作为列
    【解决方案2】:

    可能是这样的:

    SqlCommand _setvin = new SqlCommand("UPDATE Registration SET VIN=@maxId, Voted=0  WHERE UserID=@maxId", dataConnection);
    _setvin.Parameters.Add("@maxId", SqlDbType.Int).Value = maxId;
    _setvin.ExecuteNonQuery();
    

    【讨论】:

    • 对不起.. 更新了答案
    猜你喜欢
    • 2014-06-14
    • 2011-05-02
    • 1970-01-01
    • 2016-09-26
    • 2021-05-25
    • 2018-12-28
    • 2011-04-12
    • 2017-01-24
    • 2018-05-17
    相关资源
    最近更新 更多