| Author |
Checking if a record exists
|
Kody Wright
Greenhorn
Joined: Mar 06, 2011
Posts: 21
|
|
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: 16487
|
|
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: 1114
|
|
|
|
 |
 |
|
|
subject: Checking if a record exists
|
|
|