select count (*) from java executeQuery

0

How can I store the number that returns the select count (*) in a variable?

 public int contar_num_personajes() throws SQLException{
         Connection dbConnection = null ;
         Statement stm = null;
         int n= 0;
         String consulta_contar_num_personajes = "SELECT count(*)" +
                                                  "FROM personajes;";    
         dbConnection = get_conection();
         stm = dbConnection.createStatement();
         n = stm.executeQuery(consulta_contar_num_personajes);
         return n;
    }
    
asked by Selito95 16.07.2017 в 23:22
source

1 answer

2

First of all executeQuery is a method to execute a single query of type select , therefore not only is it not necessary to indicate the end of the statement with ";" but in several drivers you will get execption ORA-00911: invalid character . The reason is that ";" is not part of the syntax but a statement separator used by CLI tools. You can read more about this here

About your question:

  

How can I store the number that returns the select count to me in a   variable?

You can use ResultSet to store the result of your query.

In your query you know that you will get a single value and it is an integer, so the correct thing would be to access it through ResultSet.getInt (int) passing as a parameter the first index ( 1 )

public int contar_num_personajes() throws SQLException{ 
     int n= 0;
     Connection  dbConnection = get_conection();
     Statement stm = dbConnection.createStatement();
     // almaceno resultado de consulta en ResultSet
     ResultSet rs  = stm.executeQuery("SELECT count(*) FROM personajes");
     // chequeo que el result set no sea vacío, moviendo el cursor a la 
     // primer fila. (El cursor inicia antes de la primer fila)
     if(rs.next()) {
       //Si hay resultados obtengo el valor. 
        n= rs.getInt(1);
     }
     // libero recursos
     stm.close();
     dbConnection.close();
     return n;
}
    
answered by 16.07.2017 в 23:54