2012-04-06 120 views
2

我已经彻底搜索,但找不到我的列数据到我已使用SQL UPDATE语句初始化的变量的SET如何将变量传递给SqlCommand

下面是一段代码,导致问题:

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

请指导我如何,我可以纠正上面的注释行。

回答

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()方法完成的。

+0

与乌尔其解决方案给错误“无效列名” .. **请注意**是maxId是变量名没有列名... **和我想要设置名称为VIN的列,其值包含在maxId中** – Sana 2012-04-06 12:30:08

+0

@Sana我使用'@ maxId'作为变量,而不是列。这里涉及的列是'VIN','Voted'和'UserID'。 – Yuck 2012-04-06 12:31:17

+0

它不能在这里工作......“无效的列名'maxId'异常正在解决你的问题jx给了 – Sana 2012-04-06 12:36:50

2

也许是这样的:

SqlCommand _setvin = new SqlCommand("UPDATE Registration SET [email protected], Voted=0 WHERE [email protected]", dataConnection); 
_setvin.Parameters.Add("@maxId", SqlDbType.Int).Value = maxId; 
_setvin.ExecuteNonQuery(); 
+0

whats“cmd”here – Sana 2012-04-06 12:32:45

+0

对不起。..更新了答案 – Arion 2012-04-06 12:38:43

+0

非常感谢... :) – Sana 2012-04-06 12:57:24