0

Hi,
the problem is that my scrip stops if a duplicate key is found and i would like to know how to handle duplicate inserts into database and if founded ignore and don't insert the data or handle the type of error.

try{
     cmd.CommandText = "Insert  into subscritor .....
     cmd.ExecuteNonQuery();
                                
   }
catch (SqlException exc)
      {
               //what do i say for duplicate values?                 
      }
 throw;
2
Contributors
1
Reply
2
Views
6 Years
Discussion Span
Last Post by Ketsuekiame
0

What data type is your key? The easiest way to solve this is to have an integer key type and have it auto_increment. Then you don't have to worry about duplicate keys.

Otherwise I guess the only way is to generate your key, perform a select on the database and check if anything is returned. If not, your key is 99% safe. However, this won't work if more than one application/process/thread is working with your database as you might check with two threads, the same key. Then it's a matter of, whoever gets there first wins.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.