在使用ASP.NET中求和SQL中表的列的值时,获得例外

  • 本文关键字:ASP NET SQL 求和 sql asp.net sql-server
  • 更新时间 :
  • 英文 :


我正在尝试添加表的列的值。我的桌子看起来像这样:在此处输入图像描述

我想为特定ID添加月份列的值。我的代码看起来像这样:

  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期望使用@。

的名字

在这里,一些Microsoft文档,其中一个与您所做的非常相似的示例。

最新更新