Guest User

Guest User

  • Tech Writer
  • 37
  • 518

What is the correct way to treat the primary key exception?

May 26 2019 5:18 AM
I need to enter some data fetched from the Hattrick website (online football manager) into a database, using C#. The database structure is the following:
 
  • MatchID (which is also primary key)
  • Rating1
  • Rating2
  • ...
  • Rating16
Because the way the data are retrieved, if I enter into the database a MatchID which is already present, I am 100% that the other fields, Ratingx will have the same value, so this exception can be safely ignored, so as not to bother the user.
 
To treat this exception, I used the following code:
  1. string AddMatchCommand = "Insert into Games values (@Match, @Ratings1, @Ratings2, @Ratings3, @Ratings4, @Ratings5, @Ratings6, @Ratings7, @Ratings8, @Ratings9, @Ratings10, @Ratings11, @Ratings12, @Ratings13, @Ratings14, @Ratings15, @Ratings16)";
  2. SqlConnection MyConn = new SqlConnection(CreateTableConnectionString);  
  3. SqlCommand command = new SqlCommand(AddMatchCommand, MyConn);  
  4.    
  5. command.Parameters.AddWithValue("@Match", MatchIDToInsert.ToString(CultureInfo.InvariantCulture));  
  6. command.Parameters.AddWithValue("@Ratings1", RatingsToInsert[0].ToString(CultureInfo.InvariantCulture));  
  7. command.Parameters.AddWithValue("@Ratings2", RatingsToInsert[1].ToString(CultureInfo.InvariantCulture));  
  8. //...   
  9. command.Parameters.AddWithValue("@Ratings16", RatingsToInsert[15].ToString(CultureInfo.InvariantCulture));  
  10. MyConn.Open();  
  11. try  
  12. {  
  13. command.ExecuteNonQuery();  
  14. }  
  15. catch (SqlException S)  
  16. {  
  17. if (S.Number != 2627)  //2627 is the ID for the exception I want to ignore
  18. {  
  19. MessageBox.Show(S.Message);  
  20. }  
  21. }  
  22. MyConn.Close();  
 The code above does its job. However, is there a better way to handle this situation? I am pretty sure that I may find a bug or two down the line, but I cannot prove this.

Answers (2)