【问题标题】:How can I insert multiple rows into SQL Server using ADO.NET?如何使用 ADO.NET 将多行插入 SQL Server?
【发布时间】:2020-05-10 11:31:19
【问题描述】:

我想为同一个查询输入不同的条目,但我遇到了一个错误:

参数必须是唯一的

有什么办法解决吗?

List<int> hoursList = new List<int>{1,2,3,4,5,6,7};

string connectionString = ConfigurationManager.ConnectionStrings["db"].ConnectionString;

using (var con = new SqlConnection(connectionString))
{
    var query = @"INSERT INTO EmployeeTable (EmployeeID, ProjectID, CategoryID, SubCategoryID, Location, Date, Hours)
                  VALUES (@EmployeeID, @ProjectID, @CategoryID, @SubCategoryID, @Location, @Date, @Hours,)";

    using(var cmd = new SqlCommand(query,con))
    {
        cmd.Parameters.AddWithValue("@EmployeeID",obj.EmployeeID);
        cmd.Parameters.AddWithValue("@ProjectID", obj.ProjectID);
        cmd.Parameters.AddWithValue("@CategoryID", obj.CategoryID);
        cmd.Parameters.AddWithValue("@SubCategoryID", obj.SubCategoryID);
        cmd.Parameters.AddWithValue("@Location", obj.Location);

        for(int j = 0; j < hoursList.Count; j++)
        {
            cmd.Parameters.AddWithValue("@Hours", hoursList[j]);
            cmd.Parameters.AddWithValue("@Date", DateTime.Now.AddDays(j).ToString("yyyy/MM/dd"));

            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

【问题讨论】:

    标签: c# sql-server ado.net


    【解决方案1】:

    您不能在循环中调用 .AddParameter - 这将不断尝试一遍又一遍地添加相同的参数(相同的名称),这会导致您看到的问题。

    将参数的声明放在循环之外 - 在循环内只设置值 - 像这样:

    // define the parameters **ONCE**, outside the loop
    cmd.Parameters.Add("@Hours", SqlDbType.Int);
    cmd.Parameters.Add("@Date", SqlDbType.DateTime);
    
    for (int j = 0; j < hoursList.Count; j++)
    {
        // inside the loop, just set the **values** - not define the same
        // parameters over and over again .....
        cmd.Parameters["@Hours"].Value = hoursList[j];
        cmd.Parameters["@Date"].Value = DateTime.Now.AddDays(j);
    
        con.Open();
        cmd.ExecuteNonQuery();
        con.Close();
    }
    

    另外 - 因为@Date 很明显是一个日期 - 你应该这样对待它并将它作为DateTime 值传递给查询 - 不要在没有真正的情况下将所有内容都转换为字符串需要!!

    总体而言:这将创建多行 - 但大多数列一遍又一遍地相同。这听起来像是一个糟糕的数据库设计 - 我会检查日期和时间是否不应该分开到他们自己的表中,这样你就可以在 EmployeeTable 中有 一个 条目,并且第二个表,其中包含该员工的 0-n 个条目,只有日期和时间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-14
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 2020-11-09
      • 2017-12-23
      • 2012-12-28
      • 1970-01-01
      相关资源
      最近更新 更多