How can I get data from a table in a database and store it in variables? (Java)

1

Friends I need to obtain the information of the fields of a database and store them in variables to later manipulate them, I have been searching the internet and I found the following sentence:

ResultSet resultado = (ResultSet) sentencia.executeQuery("SELECT * FROM 'datos' ");

But it turns out that it gives me the following error "Can not find symbol symbol: statement"

I have seen that they comment in forums that this has worked for them but I do not understand why I did not, could someone help me? or else mention another method with which I can achieve the objective ... Thanks!

    
asked by Javier Saavedra 19.10.2018 в 01:38
source

1 answer

1

There are several ways to bring the information of a table by varying small things. I give you a brief example with the basic structure to make a query to the DB and pass the data to variables

public void getDatos() {

//creamos las variables que se van a utilizar teniendo en cuenta su dato primitivo (String, int, float, etc...)
String var1;
int var2;
float var3;

//encerramos el bloque del codigo en un try/catch para manejar las excepciones
try {
    // Realizamos la conexion a la BD mediante un método especifico para ello.
    Conectar();

    //Creamos el Statement y el ResulSet necesarios para leer y guardar la informacion de la tabla
    Statement stm = conn.createStatement(); //donde "conn" es una variable del tipo "Connection".
    ResultSet rs = stm.executeQuery("SELECT * FROM DATOS");

    //Toda la información está contenida en el ResulSet, ahora procedemos a pasar la info a el ArrayList
    // nos ubicamos en la primera posición del ResultSet
    rs.first();

    var1 = rs.getString(1); //primer dato (observa los datos primitivos)
    var2 = rs.getInt(2); //segundo dato
    var3 = rs.getFloat(3); //tercer dato

    //manejamos la excepcion del tipo "SQLException"
    } catch (SQLException ex) {
        System.out.println("Error: " + ex);

    } finally {

    //cerramos la conexión a la BD
    Desconectar();
    }
}

I do not recommend doing the "SELECT *" type queries to the database since it is somewhat messy and expensive in terms of resources for the database ... you have always referred to the names of the columns in the table.

    
answered by 19.10.2018 / 05:01
source