File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes Simple Question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Simple Question" Watch "Simple Question" New topic

Simple Question

Anthony Smith
Ranch Hand

Joined: Sep 10, 2001
Posts: 285
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

Joined: Dec 12, 2001
Posts: 150
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.
I agree. Here's the link:
subject: Simple Question
jQuery in Action, 3rd edition