Return code of data entered immediately after INSERT

1

I know with java to do, but I do not find anything to do this in delphi (if possible), whenever I register a new item I search for the code by SELECT MAX ('FIELD'), but I would like to know if it is possible to return the code soon after the 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();
            }
        }
    }
    
asked by anonymous 05.10.2017 / 19:54

1 answer

2

You can do this in the insert itself:

insert into TABELA default values
  returning VALOR_QUE_DESEJO_RETORNAR

So your insert will return the value you entered in the above field.

Source: link

    
05.10.2017 / 19:56