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 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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Checking if a record exists" Watch "Checking if a record exists" New topic

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

Joined: Oct 14, 2005
Posts: 19973

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.

Avi Abrami
Ranch Hand

Joined: Oct 11, 2000
Posts: 1141

I agree. Here's the link:
subject: Checking if a record exists
It's not a secret anymore!