List getResults returns list with elements equal

1

Hello.

I have the following table in mysql:

create table resultado(
data varchar(10),
premio varchar(3),
loteria varchar(5),
milhar varchar(10),
primary key(data, premio, loteria)
);

The class representing this table in Java:

public class Resultado {
    private static String data;
    private static String premio;
    private static String loteria;
    private static String milhar;
}

And the code that extracted the results to a list:

public static List<Resultado> getResultados() throws SQLException {
    List<Resultado> resultados = new ArrayList<Resultado>();
    Connection connection = ConnectionFactory.getConnection();
    String sql = "select * from resultado";
    PreparedStatement statement = connection.prepareStatement(sql);
    statement.execute();
    ResultSet resultSet = statement.getResultSet();
    while (resultSet.next()) {
        Resultado result = new Resultado();
        Resultado.setData(resultSet.getString("data"));
        Resultado.setPremio(resultSet.getString("premio"));
        Resultado.setLoteria(resultSet.getString("loteria"));
        Resultado.setMilhar(resultSet.getString("milhar"));
        resultados.add(result);
    }
    resultSet.close();
    statement.close();
    connection.close();
    return resultados;
}

But when I print to the console, all results are the same as the last result entered.

Can anyone help me?

    
asked by anonymous 22.10.2018 / 04:28

1 answer

3

You are using static on all variables:

    private static String data;
    private static String premio;
    private static String loteria;
    private static String milhar;

ous, these variables (fields) will be unique to the class, nor does it require an instance to access (in other words, the same value independent of the instance).

Remove static by making these variables in instance variables

public class Resultado {
    private String data;
    private String premio;
    private String loteria;
    private String milhar;
}

change the methods to set accordingly, eg:

public void setData(...

and their calls to access these methods:

result.setData(resultSet.getString("data"));
    
22.10.2018 / 13:47