Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Simple Question

 
Anthony Smith
Ranch Hand
Posts: 285
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got a method that adds/modifies to the db. I want it to update if a certain value for a colmun (a primary key) is present, and add otherwise...
Do I have to do two seperate queries, and if so, what is the query that will allow me to check?
 
Tina Coleman
Ranch Hand
Posts: 150
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There're a couple of ways that I've successfully used to approach this. . .
1) Assume that it exists and do an UPDATE. Then check to see the number of rows updated by executeUpdate. If 0, then do an INSERT. (This assumes that you'll generally do more Updates than inserts).
2) Depending upon your design/architecture, if you know that your object would only have knowledge of its primary key if its already been inserted, and would always have knowledge of its primary key if its been inserted, check your object's state to determine which method to execute.
3) Push the decision to a stored procedure (use CallableStatement) and let it decide within itself. Advantage: one Java statement, using compiled procedural code, rather than two Java statements (at least) with their corresponding counts or result sets.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic