Comparando ResultSet

3 respostas
erasmo_tec

Boa tarde

Estou com uma duvida na minha aplicação onde preciso inserir um dado em uma tabela se o mesmo dado não existir ainda, ou seja eu seleciono na minha tabela e se o meu result não encontrar o dado eu faço o insert.

minha duvida é justamente como comparar se meu result set não encontrou o dado fornecido.
Alguem sabe como poço fazer isso?

public boolean consultaCobrador(Perf02Pagamento perf02Pagamento) throws ClassNotFoundException, SQLException {
         ResultSet rs = pegaDeclaracao().executeQuery("select numeroContrato from tbl_fin_perf01_lote where numeroContrato='" + perf02Pagamento.getNumeroContrato() + "'");
//aqui não sei como comparar se meu select   não encontrou o contrato
// em sql ele traz 0 rows fetched agora aqui não sei como interpretar      
        if (rs !=null) {

            while (rs.next()) {
                //perf02Pagamento.setConsultaContrato(null);
                populaConsultaContrato(perf02Pagamento, rs);
            }
            
       
        }

        rs.close();



        return true;
    }

3 Respostas

yorgan

Você pode fazer algo assim:

public boolean consultaCobrador(Perf02Pagamento perf02Pagamento) throws ClassNotFoundException, SQLException {
        boolean retorno = true;
        ResultSet rs = pegaDeclaracao().executeQuery("select numeroContrato from tbl_fin_perf01_lote where numeroContrato='" + perf02Pagamento.getNumeroContrato() + "'");
        if (rs !=null) {
            //Verifica se o rs retornou pelo menos um registro. Caso tenha encontrado, coloca FALSE na variavel RETORNO
            if(rs.next()) {
               retorno = false;
            }
       
        }
        rs.close();
        return retorno ;
    }
erasmo_tec

resolvi o problema da seguinte forma

public boolean consultaSeContratoExiste(Perf02Pagamento perf02Pagamento)
            throws ClassNotFoundException, SQLException {
        ResultSet rs =
                pegaDeclaracao().executeQuery("select numeroContrato from " +
                "tbl_fin_perf01_lote where numeroContrato='"  +
                perf02Pagamento.getNumeroContrato() + "'");

        if (rs.first() == false) {
            PreparedStatement ps =
                    pegaDeclaracaoPreparada("insert into tbl_fin_perf01_lote " +
                    "(cobradorPadrao,cpfCnpj,numeroContrato,statusAntigo)" +
                    "values(?,?,?,?)");
            ps.setString(1, perf02Pagamento.getCobradorPadrao());
            ps.setString(2, perf02Pagamento.getCpfCnpj());
            ps.setString(3, perf02Pagamento.getNumeroContrato());
            ps.setString(4, perf02Pagamento.getStatusPagamento());
            boolean toReturn = ps.execute();
            ps.close();
            return toReturn;
        }
        rs.close();
        return true;
    }

se o primeiro dado do resultSet for falso quer dizer que não encontrou registro nenhum e insere o registro na tabela…

yorgan

Só acho que você juntou muitas funções nesse método.
O ideal seria você ter um que verifica se o registro existe, outro que insere e um que valide as informações e chame os métodos. Assim você poderá reutilizar eles.
Algo +/- assim:

public void inserirContrato(Perf02Pagamento perf02Pagamento) {
     boolean contratoExistente = contratoExistente(perf02Pagamento);
     if(!contratoExistente) {
         inserir(perf02Pagamento);
     }
}

public boolean contratoExistente (Perf02Pagamento perf02Pagamento) throws ClassNotFoundException, SQLException {
        boolean retorno = false;
        ResultSet rs = pegaDeclaracao().executeQuery("select numeroContrato from tbl_fin_perf01_lote where numeroContrato='" + perf02Pagamento.getNumeroContrato() + "'");
        if (rs !=null) {
            //Verifica se o rs retornou pelo menos um registro. Caso tenha encontrado, coloca FALSE na variavel RETORNO
            if(rs.next()) {
               retorno = true;
            }
       
        }
        rs.close();
        return retorno ;
}

public void inserir(Perf02Pagamento perf02Pagamento) throws ClassNotFoundException, SQLException {
            PreparedStatement ps =
                    pegaDeclaracaoPreparada("insert into tbl_fin_perf01_lote " +
                    "(cobradorPadrao,cpfCnpj,numeroContrato,statusAntigo)" +
                    "values(?,?,?,?)");
            ps.setString(1, perf02Pagamento.getCobradorPadrao());
            ps.setString(2, perf02Pagamento.getCpfCnpj());
            ps.setString(3, perf02Pagamento.getNumeroContrato());
            ps.setString(4, perf02Pagamento.getStatusPagamento());
            ps.execute();
            ps.close();

}

[]´s

Daniel

Criado 14 de julho de 2009
Ultima resposta 15 de jul. de 2009
Respostas 3
Participantes 2