![](/img/trans.png)
[英]Multiple Insert transaction connection timeout - ADO.NET - SQL Server
[英]How can I insert multiple rows into SQL Server using ADO.NET?
我想为同一个查询输入不同的条目,但是我遇到了错误的小时数和日期:
参数必须是唯一的
有什么办法吗?
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
值传递给查询 - 不要在没有真正需要的情况下将所有内容转换为字符串!
总体而言:这将创建多行 - 但大多数列一遍又一遍地相同。 这闻起来像是一个糟糕的数据库设计 - 我会检查日期和时间是否不应该分开到他们自己的表中,这样你就可以在EmployeeTable
中有一个条目,第二个表包含 0-n 个条目对于该员工,只有日期和时间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.