Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I tell if a row exists in a table?

Tags:

java

sql

jdbc

For example:

select name from person where id=2;

I wand to know if this row exists, and depending on its existence perform a certain task. I wan to do this using jdbc.

like image 511
uday gowda Avatar asked Jul 02 '12 06:07

uday gowda


People also ask

How do I find a specific row in SQL?

To select rows using selection symbols for character or graphic data, use the LIKE keyword in a WHERE clause, and the underscore and percent sign as selection symbols. You can create multiple row conditions, and use the AND, OR, or IN keywords to connect the conditions.

How do you check if data not exists in a table SQL?

SQL NOT EXISTS in a subquery NOT EXISTS is used with a subquery in the WHERE clause to check if the result of the subquery returns TRUE or FALSE. The Boolean value is then used to narrow down the rows from the outer select statement.


2 Answers

Use PreparedStatement to invoke this select query,

After the successful execution of query you would have instance of ResultSet returned, you could check by invoking next() if it returns true it means there was a row selected

if(resultSet.next()){
   //yes exist
}
like image 152
jmj Avatar answered Sep 23 '22 19:09

jmj


The is no hasNext() method in ResultSet. The next() method moves the cursor to the next row and if there is a row then it returns true.

if(resultSet.next()){
  //do something

}
else{
  //no next row found

}
like image 25
Moinul Hossain Avatar answered Sep 24 '22 19:09

Moinul Hossain