如何使用 ADO.NET 将多行插入 SQL 服务器?

How can I insert multiple rows into SQL Server using ADO.NET?

我想为同一个查询创建不同的条目,但是我 运行 的时间和日期出现错误:

Parameters must be unique

有什么办法吗?

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

您不能在循环中调用 .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 值传递到查询中 -不要在没有真正需要的情况下将所有内容都转换为字符串!!

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