我正在使用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