如何将变量传递给SqlCommand

时间:2022-01-24 15:09:24

I have searched thoroughly, but could not find a way to SET my column data to the variable that I have initialized using a SQL UPDATE statement.

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

Here is the piece of code that is causing problem:

以下是导致问题的代码段:

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

Please guide me on how I can correct the commented line above.

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

2 个解决方案

#1


2  

Maybe something like this:

也许是这样的:

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

#2


1  

I think you're trying to do this:

我想你正试图这样做:

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

You need to first change your SQL statement to include a parameter for the maxId; I'm calling that @maxId in your SQL. Then you need to supply a value for that parameter to the command. This is done with the Parameters.AddWithValue() method.

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

#1


2  

Maybe something like this:

也许是这样的:

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

#2


1  

I think you're trying to do this:

我想你正试图这样做:

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

You need to first change your SQL statement to include a parameter for the maxId; I'm calling that @maxId in your SQL. Then you need to supply a value for that parameter to the command. This is done with the Parameters.AddWithValue() method.

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