我正在使用C#编写Windows窗体项目。我正尝试从数组中插入多个记录到SQL Server数据库中。使用for循环插入多个记录到SQL Server数据库中
进入第一行后,我得到一个异常
@UserID已经宣布。变量名称在查询批处理或存储过程中必须是唯一的。
数据库中的主键没有问题,因为UserID
不是主键。
这就是我想要做的。
public static void featuresentry()
{
SqlConnection connection = new SqlConnection(HandVeinPattern.Properties.Settings.Default.HandVeinPatternConnectionString);
SqlCommand command = new SqlCommand();
connection.Open();
try
{
command = connection.CreateCommand();
for (int i = 0; i < Details.modelKeyPoints.Size; i++)
{
command.CommandText = "INSERT INTO FEATURES(UserID, Angle, ClassID, Octave, PointX, PointY, Response, Size) VALUES(@UserID, @Angle, @ClassID, @Octave, @PointX, @PointY, @Response, @Size)";
command.Parameters.AddWithValue("@UserID", Details.ID);
command.Parameters.AddWithValue("@Angle", Convert.ToDouble(Details.modelKeyPoints[i].Angle));
command.Parameters.AddWithValue("@ClassID", Convert.ToDouble(Details.modelKeyPoints[i].ClassId));
command.Parameters.AddWithValue("@Octave", Convert.ToDouble(Details.modelKeyPoints[i].Octave));
command.Parameters.AddWithValue("@PointX", Convert.ToDouble(Details.modelKeyPoints[i].Point.X));
command.Parameters.AddWithValue("@PointY", Convert.ToDouble(Details.modelKeyPoints[i].Point.Y));
command.Parameters.AddWithValue("@Response", Convert.ToDouble(Details.modelKeyPoints[i].Response));
command.Parameters.AddWithValue("@Size", Convert.ToDouble(Details.modelKeyPoints[i].Size));
command.ExecuteNonQuery();
}
}
catch (Exception)
{
throw;
}
finally
{
if (connection.State == ConnectionState.Open)
{
connection.Close();
}
}
}
我想,如果你把'命令= connection.CreateCommand();'里面的for循环,它会工作。问题是你只循环了命令参数,所以它试图向现有的命令添加更多的参数,但它们已经在那里。所以你需要在每个循环中创建一个新的命令。 –
@UnicornoMarley,是的,这是问题。很好的捕获,发布作为答案。 – Rahul
另一种选择是将所有的命令和参数创建移到循环之外,只更新值并在循环内执行。这样你就不会持续创建对象的新实例。 – gmiley