• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Get or Insert

 
Brian Shultz
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am trying to create a method that either gets and Id or inserts the a new row, what i have works some of the time but not all the time. sometimes i get a Duplicate Key message back. The table is keyed on the combination of identifierref and object_type_id, can anyone recommend a better more stable way, This is using the SQLServerDriver class for 2005 and Microsoft SQL Server 2000. Thank you in advance.

 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34974
379
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Brian,
Welcome to JavaRanch!

It looks like the duplicate key exception is thrown when two callers execute the code at the same time. This could happen if you have the following sequence of events:
1) You check if record exists and it doesn't
2) Another thread inserts a record with that key
3) You insert the record and get a duplicate key exception

Take a look at transactions to eliminate this scenario.
 
Brian Shultz
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thankyou,
That makes sense, so would the best way around this be a try catch that looks for duplicate key again, and then if caught try to select it and if not found try to insert it again. Or is there a good way around this at all?
Thanks
_Brian
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic