我试图添加表的列的值。我的表看起来像这样:enter image description here
我想为特定ID添加months列的值。我的代码看起来像这样:
public int MonthSum(int id)
{
SqlConnection connection = new SqlConnection(connectionString);
string query = "select sum(months) from PayTable where ID=@ID group by ID";
SqlCommand command = new SqlCommand(query,connection);
command.Parameters.Clear();
command.Parameters.Add("ID", SqlDbType.Int);
command.Parameters["ID"].Value = id;
connection.Open();
int total = (int)command.ExecuteScalar();
connection.Close();
return total;
}
为什么我在这里得到例外?
由于您没有提供有关异常的更多信息,因此只能进行猜测,但您可能无法将参数添加为“ID”而不是“@ID”。我认为SqlCommand期望带有@的名称。
Here一些Microsoft文档,其示例与您正在执行的操作非常相似。