Save data to DB and recover ID automatically

Asked

Viewed 133 times

1

This is the code to save to the bank using the default DAO, where I want to recover the id record to save the table Usuario who owns the FOREIGN KEY table Habilitacao:

public int insertDados(Habilitacao c) {
        int registros;

        try{
            pstm = conn.getConnection().prepareStatement(SQL_INSERT);
            pstm.setString(1, c.getNumero_regs());
            pstm.setString(2,c.getCategoria());
            pstm.setString(3,c.getData_Emissao());
            pstm.setString(4,c.getData_Primeira());
            pstm.setString(5,c.getData_Validade());
            registros = pstm.executeUpdate();

            PreparedStatement pstmAux;
            pstmAux = conn.getConnection().prepareStatement(
                                          "SELECT @@IDENTITY");     
            rs = pstmAux.executeQuery();

            int codigo = 0;

            if((registros == 1)&&(rs !=null)){
                rs.next();
                codigo = rs.getInt(1);
                return codigo;
            }else{
                return codigo;
            }
        }catch(Exception error){

            Logger.getLogger(HabilitacaoDao.class.getName()).log(
                             Level.SEVERE, null, error);
            throw new RuntimeException(" Falha ao selecionar pessoas",
                                       error);
        }finally{
            //ConnectionSingleton.Desconetar(null, pstm, rs);
        }

This is the code to execute the DAO, fill in the fields and save, but the ID_habilitacao is not being recovered:

public void inserirHabilitacao(Habilitacao h){
    //acao =1;
    int cod;
    try{
        preencherCamposCnh();
        habilitacaoDao = new HabilitacaoDao();

        if( acao == 1){
            cod = habilitacaoDao.insertDados(habilitacao);
            codCnh.setText(String.valueOf(cod));
            JOptionPane.showMessageDialog(this, "Salvo com sucesso");
            inicioTela();
    }}catch(HeadlessException error){

        JOptionPane.showMessageDialog(this,
          "Erro ao salvar Dados Habilitação" + error.getMessage());
    }
    try{
        preencherCamposCnh();
        // acao = 2;
        habilitacaoDao = new HabilitacaoDao();

        if( acao == 2){
            jftDataPrimeiraHab.setEnabled(false);
            codCnh.setEnabled(false);
            jtfNumCnh.setEnabled(false);
            habilitacaoDao.alterar(habilitacao);          
            JOptionPane.showMessageDialog(this, "Aterado com sucesso");
            inicioTela();
        }
    }catch(HeadlessException error){
        JOptionPane.showMessageDialog(this,
          "Erro ao editar Habilitação" + error.getMessage());
    }
}

1 answer

0

@@IDENTITY is used by SQL Server and not by Mysql

pstmAux = conn.getConnection().prepareStatement("SELECT @@IDENTITY");  

To recover the id of records inserted in Mysql use LAST_INSERT_ID()

pstmAux = conn.getConnection().prepareStatement("SELECT  LAST_INSERT_ID()");  
  • 1

    That was the problem. Thank you

Browser other questions tagged

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