How to know in JAVA that ResultSet result is empty?

4

I am searching the database, and I have problem with SQL returning an empty value. In fact it is possible that this happens and for this I must keep prepared for it. What method to identify that no record was found with that parameter?

I tried to use TRY/CATCH but it did not work.

My code looks 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();
    
asked by anonymous 01.02.2016 / 12:08

2 answers

5

You can use next . 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 take advantage of 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 ResultSetMetaData . It has all the data from the result set. But it would be better already to know if there was any result. You can get a lot more data with this, how many columns, what kind, the table name, and more, take a look at Javadoc (maybe you already know it)

    
01.02.2016 / 12:22
4

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

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

So if this method is called right after doing the query and it returns false , then it is indicative that no records were returned for the query performed.

Example:

if (!resultSet.isBeforeFirst()) 
   System.out.println("Não há registros."); 
    
01.02.2016 / 18:30