TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Guest User
Tech Writer
37
906
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, Rating
x
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:
string AddMatchCommand = "Insert into Games values (@Match, @Ratings1, @Ratings2, @Ratings3, @Ratings4, @Ratings5, @Ratings6, @Ratings7, @Ratings8, @Ratings9, @Ratings10, @Ratings11, @Ratings12, @Ratings13, @Ratings14, @Ratings15, @Ratings16)";
SqlConnection MyConn =
new
SqlConnection(CreateTableConnectionString);
SqlCommand command =
new
SqlCommand(AddMatchCommand, MyConn);
command.Parameters.AddWithValue(
"@Match"
, MatchIDToInsert.ToString(CultureInfo.InvariantCulture));
command.Parameters.AddWithValue(
"@Ratings1"
, RatingsToInsert[0].ToString(CultureInfo.InvariantCulture));
command.Parameters.AddWithValue(
"@Ratings2"
, RatingsToInsert[1].ToString(CultureInfo.InvariantCulture));
//...
command.Parameters.AddWithValue(
"@Ratings16"
, RatingsToInsert[15].ToString(CultureInfo.InvariantCulture));
MyConn.Open();
try
{
command.ExecuteNonQuery();
}
catch
(SqlException S)
{
if
(S.Number != 2627) //2627 is the ID for the exception I want to ignore
{
MessageBox.Show(S.Message);
}
}
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.
Reply
Answers (
2
)
How to implement redux in c#?
How to integrated Whatsapp bot reply(Like Red bus..)