This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes JDBC and the fly likes Checking if a record exists Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Checking if a record exists" Watch "Checking if a record exists" New topic
Author

Checking if a record exists

Kody Wright
Ranch Hand

Joined: Mar 06, 2011
Posts: 32
Hello : )

I've been having trouble writing this code that should be relatively simple. I'm wanting to check if a record exists, if it does then it is deleted, if not then a JOptionPane shows up. My experience in SQL is limited but I don't think this should require much SQL knowledge in the first place to execute. I've spent a deal of time on the internet looking for solutions, but I am never able to successfully implement them into my code. Is there a simple way to do this that I am overlooking? I'll post the code of the method below in case it helps.

Thanks in advance for your time and help!



Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

The first query will always return exactly one record. (The value of COUNT(*) will be zero if the query didn't count any records, but there will still be one record containing that zero.)

But I don't see why you're trying to find out if a record exists. Just execute the delete statement and be done with it. (Although you should use the executeUpdate method instead; it returns a number which tells you how many records were deleted. Which might be zero.)
Mike Zal
Ranch Hand

Joined: May 04, 2011
Posts: 144

Like Paul said, if you are deleteing something from a database, there is no need to check if it already exists. If a record does not exist, then the command does nothing. Calling executeUpdate will return the number of rows that were modified by the call. Here is some psuedo code


You might also consider declaring your connection and statements outside the try statement so that you can close them in a finally block. Right now, if your code produced an exception, the connection would stay open.

You should be using a java.sql.PreparedStatement instead of a regular Statement. It offers protection against sql injection attacks. Look at the beginning of the javadoc for an example.


OCJP6, OCWCD5
Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1121

 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Checking if a record exists
 
Similar Threads
Can't Update Record ?
Database update
Can't Update Record ?
problem with gui
The INSERT INTO statement contains the following unknown field name: 'OPANo'.