Save data to DB and retrieve ID automatically [duplicate]

1

This is the code to save to the database using the DAO pattern, where I want to already recover the id of the registry in order to save the Usuario table that has FOREIGN KEY of the Habilitacao table: p>

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 run DAO , fill in the fields and save, but ID_habilitacao is not being retrieved:

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());
    }
}
    
asked by anonymous 28.10.2015 / 16:20

1 answer

0

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

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

To retrieve the id of the records inserted in MySQL use LAST_INSERT_ID()

pstmAux = conn.getConnection().prepareStatement("SELECT  LAST_INSERT_ID()");  
    
30.10.2015 / 12:26