Java/Postgresql - Function does not return values

Asked

Viewed 148 times

1

I am creating a webservice where I will return the values of my postgresql table. However, when I run this function, a blank screen appears as if there were no data to be returned. I purposely tested the connection data as driver, user, password, bd etc. and tbem tried to include errors in the select command itself, but when I make a mistake in any of these data, it ends up presenting a different error. The codes below are with the correct information, but even so does not present an error message, only the blank screen without information.

I think it might be some wrong configuration in postgresql itself, however I have already configured it to have external access in pg_hba.conf and postgresql.conf files and even then there were no changes.

# IPv4 local connections:
host     all     all     127.0.0.1/32    md5
host     all     all     0.0.0.0/0   md5
# IPv6 local connections:
host    all         all         ::1/128               md5

# - Connection Settings -

listen_addresses = '*'      # what IP address(es) to listen on;

Function used=

public List<Usuario> listar()
    {
         String sql = "SELECT * FROM Usuario";
        List<Usuario> retorno = new ArrayList<Usuario>();

        PreparedStatement pst = Conexao.getPreparedStatement(sql);
        try {


            ResultSet res = pst.executeQuery();
            while(res.next())
            {
                Usuario item = new Usuario();
                item.setLogin(res.getString("Login"));
                item.setSenha(res.getString("Senha"));
                item.setEmail(res.getString("Email"));
                item.setNome(res.getString("Nome"));

                retorno.add(item);
            }



        } catch (SQLException ex) {
            Logger.getLogger(UsuarioDAO.class.getName()).log(Level.SEVERE, null, ex);

        }

        return retorno;


    }

User class =

public class Usuario {

    private String Login;
    private String Senha;
    private String Email;
    private String Nome;

    public String getLogin() {
        return Login;
    }

    public void setLogin(String Login) {
        this.Login = Login;
    }

    public String getSenha() {
        return Senha;
    }

    public void setSenha(String Senha) {
        this.Senha = Senha;
    }

    public String getEmail() {
        return Email;
    }

    public void setEmail(String Email) {
        this.Email = Email;
    }

    public String getNome() {
        return Nome;
    }

    public void setNome(String Nome) {
        this.Nome = Nome;
}

}

Class of Connection=

public class Conexao {

    private static final String banco = 
            "jdbc:postgresql://localhost:5433/OniPresente";
    /**
     * O atributo driver representa a classe do Driver JDBC que será usada na 
     * conexão. Quando se utiliza outros bancos usa-se a classe apropriada a 
     * cada banco
     */
    private static final String driver = 
            "org.postgresql.Driver";
    /**
     * Os atributos usuario e senha representam usuario e senha do 
     * SGBD a ser usado na conexão
     */
    private static final String usuario = "postgres";
    private static final String senha = "1234";  
    /**
     * O atributo con representa um objeto que 
     * contém a conexão com o banco de dados em si
     */
    private static Connection con = null;

    /**
     * Metodo que retorna uma conexão com o banco de dados
     * @return objeto java.sql.Connection
     */
    public static Connection getConexao(){
        // primeiro testo se o objeto con não foi inicializado
        if (con == null){
            try {
                // defino a classe do driver a ser usado
                Class.forName(driver);
                // criação da conexão com o BD
                con = 
                DriverManager.getConnection(
                        banco, usuario, senha);
            } catch (ClassNotFoundException ex) {
                System.out.println("Não encontrou o driver");
            } catch (SQLException ex) {
                System.out.println("Erro ao conectar: "+
                        ex.getMessage());
            }
        }
        return con;
    }
    /**
     * Método que recebe um comando SQL para ser executado
     * @param sql
     * @return um objeto java.sql.PreparedStatement
     */
    public static PreparedStatement getPreparedStatement(String sql){
        // testo se a conexão já foi criada
        if (con == null){
            // cria a conexão
            con = getConexao();
        }
        try {
            // retorna um objeto java.sql.PreparedStatement
            return con.prepareStatement(sql);
        } catch (SQLException e){
            System.out.println("Erro de sql: "+
                    e.getMessage());
        }
        return null;
}

Bench=

CREATE TABLE "Usuario"
(
  "IdUsuario" integer NOT NULL,
  "Login" character varying(20),
  "Senha" character varying(20),
  "Nome" character varying(50),
  "Chave" character varying(20),
  "DtNasc" date,
  "Fone" character varying(11),
  "Email" character varying(30),
  "OAB" character varying(10),
  "Endereco" character varying(50),
  "Bairro" character varying(20),
  "CEP" character varying(10),
  "CodCidade" integer,
  "CPF" character varying(15),
  "CNPJ" character varying(20),
  CONSTRAINT pk_usuario PRIMARY KEY ("IdUsuario")
)
WITH (
  OIDS=FALSE
);
ALTER TABLE "Usuario" OWNER TO postgres;
  • Tried to debug? Checks if the return variable is being populated

  • Read this answer and also this other to get ideas on how to improve your code. However, these answers may not yet be enough to solve your problem.

No answers

Browser other questions tagged

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