Return code from data entered just after INSERT

Asked

Viewed 105 times

1

i know with java to do, but I did not find anything to do this in Delphi(if possible), whenever and register a new item I search the code by SELECT MAX('FIELD'), but I wonder if it is possible to return the code right after INSERT:

Java example:

public int inserirOperacao(Pedido pedido){
        try{
            conn = ConectaMySql.obtemConexao();
            String insereOperacao = "INSERT INTO PEDIDO VALUES (null, ?, ?, ?, 'P', 'A')";

            stmt = conn.prepareStatement(insereOperacao, Statement.RETURN_GENERATED_KEYS);
            stmt.setInt(1, pedido.getLogCodigo());
            stmt.setString(2, pedido.getPedObservacao());
            stmt.setString(3, pedido.getPedEndereco());

            int affectedRows = stmt.executeUpdate();

            if (affectedRows == 0) {
                return -1;
            }

            try(ResultSet generatedKeys = stmt.getGeneratedKeys()){
                if(generatedKeys.next()){
                    return (int) generatedKeys.getLong(1);
                }else{
                    return -1;
                }
            }catch (Exception e) {
                e.printStackTrace();
                return -1;
                // TODO: handle exception
            }
        }catch (Exception e) {
            e.printStackTrace();
            return -1;
            // TODO: handle exception
        }finally {
            try {
                if(stmt != null){
                    stmt.close();
                }
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

1 answer

2


  • I just don’t understand how I play the value returned into a variable would be: Insert into TABLE default values returning VALOR_QUE_DESEJO_RETORNAR INTO VARIABLE?

  • Put the excerpt of the code in dephi that you are using to make the query that I try to help.

  • for example: Insert into PRODUCT (DESCRIPTION, PRICE) values ('CHOCOLATE', '7.50');

  • Which field do you want Insert to return? from the table I say.

  • the code of the product that is generated by auto increment

  • No problem, what is the name of the field in the table?

  • field name is CODE

  • @Luizsantos Interesting the use of returning in Fdquery for Firebird +1

  • Thanks :) @Paz I think it’s a good solution

Show 5 more comments

Browser other questions tagged

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