I have a table with some columns and I've set Unique Key on 3 of those columns to make sure there are no duplicates in the table. Now I was wondering if using try / catch to swallow exceptions throw on duplicates and continue updating inserting next rows in foreach
is a good way to go?
try {
sqlWrite.ExecuteNonQuery();
} catch (SqlException sqlException) {
if (!sqlException.ToString().Contains("Violation of UNIQUE KEY constraint")) {
MessageBox.Show("Error - " + Environment.NewLine + sqlException.ToString(), "Error SQL");
}
} catch (Exception exception) {
MessageBox.Show("Error - " + Environment.NewLine + exception.ToString(), "Error SQL");
}
Or should I do SELECT inside insert query to check if row exists and if it does skip insert? I have read that it's not good to use exceptions as part of your data verification but some things are supposed to be used like that (for example How to check For File Lock in C#? is supposed to be used with try/catch).