Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Checking if a record exists

 
Kody Wright
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 144
Fedora Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1141
1
Java Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic