How do I know in JAVA that the Resultset result is empty?

Asked

Viewed 5,185 times

4

I’m running it through the database, and I have a problem SQL return an empty value. It is actually possible for this to happen and therefore I need to keep ready for it. Which method to identify that no record with that parameter was found ?

I’ve tried using the TRY/CATCH but it didn’t work.

My code is like this:

 ResultSet rs_tbl_PESSOAS = con.query("SELECT * FROM tbl_PESSOAS WHERE XXXX= '" + w_obj.getString("XXXX") + "' and COD_IDENT_PESSO = '" + w_obj.getString("COD_IDENT_PESSO") + "';");
                    ResultSetMetaData rsmd = rs_tbl_PESSOAS.getMetaData();
                    int columnsNumber = rsmd.getColumnCount();
  • What Voce wants is to check if the query did not return results to the correct result set?

  • I want to get to if there are data returned in this query. If the database returned some line in SQL

3 answers

6


You can use next . Is usually used :

white(resultSet.next()){
   //Percorrer o resultado da sql
}

What happens is that if there are no results the first next will return false. And you can enjoy doing the following:

if(resultSet.next()){
   //Se passar ele vai estar na posicao 1 , já pronto para usar os getters
   do{
      //codigo
   }while(resultSet.next());
}else{
   //Se nao passar significa que não houve resultados
}

You can also use the Resultsetmetadata . It has all the data from the result set. But it would be better to know if there were any results. You can get a lot more data with this, how many columns, what type, table name and more, take a look at Javadoc(you may already know , however)

  • The problem if using next, it will pass to the next stack line if there is any positive feedback.

  • The resultset starts in an unusable position, the first next moves to the first position, don’t forget it! But even so, in that case you could use DO WHILE after if. So you wouldn’t skip the first.

5

Another option is to use the method isBeforeFirst() also of class ResultSet.

This method will return true if the cursor is before the first record and false if the cursor is in any position or if there are no records.

Therefore, if this method is called right after making the query and he return false, then it is indicative that no records were returned to the query performed.

Example:

if (!resultSet.isBeforeFirst()) 
   System.out.println("Não há registros."); 

0

After the while(){}

Try a check if the resultSet traveled to the last, IE, whether found records or not:

if(!resultSet.isAfterLast()){}

If the resultset contains no lines the above condition will be true, serving as an "Else" for the while above.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.