List<> getResults returns list with equal elements

Asked

Viewed 67 times

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 that represents 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 extracts 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 printing on the console, all results are equal to the last entered result.

Can someone help me?

1 answer

3


Are you using static in all variables:

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

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

Remove the static turning these variables into instance variables

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

change the methods to set according, example:

public void setData(...

and their calls to access these methods:

result.setData(resultSet.getString("data"));
  • 1

    It worked here. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.