如何将变量传递给SqlCommand

如何将变量传递给SqlCommand,sql,sql-server,c#-4.0,ado.net,sqlcommand,Sql,Sql Server,C# 4.0,Ado.net,Sqlcommand,我已经彻底搜索过了,但找不到方法将我的列数据设置为使用SQLUPDATE语句初始化的变量 下面是导致问题的一段代码: int maxId; SqlConnection dataConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString) ; SqlCommand dataCommand = new SqlCommand("select m

我已经彻底搜索过了,但找不到方法将我的列数据设置为使用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();

请指导我如何更正上面的评论行。

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

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
。然后需要为该命令提供该参数的值。这是通过以下方法完成的。

可能类似于:

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();

在您的解决方案中,给出错误“无效列名”。。请注意,maxId是变量名而不是列名**我想用maxId**@Sana中包含的值设置名为VIN的列,我使用的是
@maxId
作为变量,而不是列。此处涉及的列有
VIN
voated
UserID
。此处不起作用。。。解决方案u jx捕获到无效列名“maxId”异常gave@Sana那么您没有正确复制我的代码,因为我没有将
maxId
作为一列引用。对此表示抱歉..更新了答案