Fbsqlexception in the INSERT method with Returning

Asked

Viewed 24 times

0

I’m trying to make an INSERT in my bank (Firebird) with Returning to return the registered ID, however, when it arrives at the line stmt.executeUpdate() i get the Exception Fbsqlexception.

Insert method:

Note 1: I am using netbeans.

public int insereBanco(BancoCTR bancoCTR) {
        try {
            conn = Conexao.obtemConexao();
            String insert = "INSERT INTO BANCO VALUES (null, ?) RETURNING "
                    + "BCO_CODIGO";

            stmt = conn.prepareStatement(insert);
            stmt.setString(1, bancoCTR.getBcoNome());
            int i = stmt.executeUpdate();


            if (i < 1){
                return -1;
            }else{
                rSet = stmt.executeQuery();
            }


            if (rSet.next()) {
                return rSet.getInt(1);
            } else {
                return -2;
            }

        } catch (Exception e) {
            System.out.println("Erro ao inserir banco: " + e.getMessage());
            return -3;
        }
    }

1 answer

0

As the returning that was causing the problem, I solved with a gambiarra.

I’ll leave it here in case someone else doesn’t find a proper way to solve it either:

public int insereBanco(BancoCTR bancoCTR) {
        try {
            conn = Conexao.obtemConexao();
            String insert = "INSERT INTO BANCO VALUES (null, ?)";

            stmt = conn.prepareStatement(insert);
            stmt.setString(1, bancoCTR.getBcoNome());
            int i = stmt.executeUpdate();


            if (i < 1){
                return -1;
            }else{
                //Gambiarra ====================================================
                stmt = null;
                String codigo = "SELECT MAX(BCO_CODIGO) FROM BANCO";

                stmt = conn.prepareStatement(codigo);                
                rSet = stmt.executeQuery();
                //==============================================================
            }           

            if (rSet.next()) {
                return rSet.getInt(1);
            } else {
                return -2;
            }

        } catch (Exception e) {
            System.out.println("Erro ao inserir banco: " + e.getMessage());
            return -3;
        }finally{
            try{
            conn.close();
            }catch(Exception e){
                System.out.println("Erro ao fechar conexão: " + e.getMessage());
                return -4;
            }
        }
    }

Browser other questions tagged

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