简体   繁体   中英

How to convert a integer[] from PostgreSQL to a int[] in Java?

I need to get the integer[] value, from an column named "jogos" in PostgreSQL, and store it in a int[] attribute in Java, but the resultSet.getArray show me this error:

incompatible types: Array cannot be converted to int[]

And there's no resultSet.getIntegerArray or something like that.

My function:

public ResultSet LogarUsuario(Usuario usuario){
    String sql = "Select * FROM usuario WHERE email = '" + usuario.email + "' AND senha = '" + usuario.senha + "'";
    try {
        ResultSet rs = db.ExecutaBusca(sql); //search on DB and returns the result
        usuario.setId(rs.getInt("id"));
        usuario.setEmail(rs.getString("email"));
        usuario.setSenha(rs.getString("senha"));
        usuario.setJogos(rs.getArray("jogos")); //Line where is the problem
        return rs;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

My class I will instantiate and store those values from DB:

public class Usuario {
    public int id;
    public String email;
    public String senha;
    public int[] jogos;

}

So, how can I get this integer[] value and store in a int[] attribute?

There's more code I guess is not needed, but I can send a specific part if requested.

It's my first question here, sorry if something it's confusing. Also, sorry if my english looks weird or wrong, I am still learning.

Try something like this

 Array array = rs.getArray("jogos");
 usuario.setJogos((int[]) array.getArray());

The getArray method may be returning Array Objects, so you may need to use Integer wrapper for the variable to set the value into. You are using primitive int array in the class where you store the values. Try this , may work (not tested)

Modify this:

public int[] jogos;

To:

public Integer[] jogos;
public Integer[] getJogos() {
    return jogos;
}
public void setJogos(Integer[] jogos) {
    this.jogos = jogos;
}

Modify this :

usuario.setJogos(rs.getArray("jogos"));` //Line where is the problem

To:

Array jogosArray= rs.getArray("jogos");
Integer[] jogosIntArray = (Integer[]) jogosArray.getArray();
usuario.setJogos(jogosIntArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM