I'm trying to list data from my bank, more precisely from column cpf, but I can only bring a given

0
List < VarUnica > list = new ArrayList < VarUnica > ();
    String queri = "select cpf from funcionario";
    VarUnica alt = new VarUnica();
    Statement ttpa;
    try {
        ttpa = Conexao.getConexao().createStatement();
        ResultSet tr = ttpa.executeQuery(queri);
        while (tr.next()) {
            alt.setRp(tr.getString("cpf"));

            list.add(alt);
        }
        for (VarUnica c: list) {
            System.out.println(alt.getRp());

        }

    } catch (SQLException ex) {
        Logger.getLogger(InserindoDados.class.getName()).log(Level.SEVERE, null, ex);
    }
}
    
asked by anonymous 06.05.2016 / 20:50

1 answer

4

You need to instantiate your object within While because that way you will create a new object before putting it in a list. In your FOR you need to use the instance variable that was created in for.

for (VarUnica c: list) {
   //c represnta o objeto dentro dessa iteração
   System.out.println(c.getRp());
}

The complete Code would look like this:

List <VarUnica> list = new ArrayList <VarUnica> ();
    String queri = "select cpf from funcionario";
    Statement ttpa;
    try {
        ttpa = Conexao.getConexao().createStatement();
        ResultSet tr = ttpa.executeQuery(queri);
        while (tr.next()) {
            //Criando um novo objeto a cada iteração
            VarUnica alt = new VarUnica();
            alt.setRp(tr.getString("cpf"));
            list.add(alt);
        }
        for (VarUnica c: list) {
            System.out.println(c.getRp());
        }

    } catch (SQLException ex) {
        Logger.getLogger(InserindoDados.class.getName()).log(Level.SEVERE, null, ex);
    }
}
    
06.05.2016 / 21:23