如何使用ADO.NET在SQL Server中插入多条记录?

问题描述 投票:0回答:1

我想为这个相同的查询创建不同的条目,但在小时和日期方面,我遇到了一个错误。

参数必须是唯一的

有什么办法解决这个问题吗?

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# ado.net
1个回答
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条,只有日期和小时。

© www.soinside.com 2019 - 2024. All rights reserved.