[英]How can I insert multiple rows into SQL Server using ADO.NET?
I want to make different entries for this same query but with hours and dates I ran into an error:我想为同一个查询输入不同的条目,但是我遇到了错误的小时数和日期:
Parameters must be unique
参数必须是唯一的
Is there any way around it?有什么办法吗?
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();
}
}
}
You cannot call the .AddParameter
inside your loop - that'll keep trying to add the same parameter (same name) over and over again and that causes the problems you're seeing.您不能在循环中调用
.AddParameter
- 这将不断尝试一遍又一遍地添加相同的参数(相同的名称),这会导致您看到的问题。
Put the declaration of the parameter outside the loop - and inside the loop just se the values - like this:将参数的声明放在循环之外- 在循环内只设置值 - 如下所示:
// 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();
}
Also - since @Date
quite clearly is a date - you should treat it as such and pass it into the query as a DateTime
value - don't convert everything to string without really needing to!!另外 - 因为
@Date
很明显是一个日期- 你应该这样对待它并将它作为DateTime
值传递给查询 - 不要在没有真正需要的情况下将所有内容转换为字符串!
And overall: this will create multiple rows - but most of the columns are the same over and over again.总体而言:这将创建多行 - 但大多数列一遍又一遍地相同。 This smells like it's a bad database design - I would check if the date and hours shouldn't be separated out into their own tables, so that you'd have one entry in the
EmployeeTable
, and a second table which holds 0-n entries for that employee, with just date and hours.这闻起来像是一个糟糕的数据库设计 - 我会检查日期和时间是否不应该分开到他们自己的表中,这样你就可以在
EmployeeTable
中有一个条目,第二个表包含 0-n 个条目对于该员工,只有日期和时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.