last question id inserted (mysql)

2

Hello, good morning, everyone.

I need to make an insert to an X table and immediately make an insert in an Xx table. The insert to the first table works without problems, but the particularity that the second insert has as key the ID that generated the first insert , so it occurs to me that before of the second insert I must obtain the ID that generated the first insert .

I was seeing that mysql has a function (last_insert_id) but I did not understand the use very well. Should I go to the query where I do the insert ? or should I create a method (a select ) with this function?

I work with c # and mysql and for insert I use stored procedures.

Save button code:

        private void btnGuardar_Click(object sender, EventArgs e)
    {
        try
        {
            string respuesta = "";

            //validamos los campos obligatorios
            if (this.txtCodFuncionario.Text == string.Empty || this.txtIDHorario.Text == string.Empty ||
                this.txtCodPaciente.Text == string.Empty
                )
            {
                mensajeError("Faltan datos por ingresar, favor verificar");
                error.SetError(txtCodPaciente, "Debe seleccionar o ingresar el Codigo del Paciente");
                error.SetError(txtIDHorario, "Debe seleccionar un horario de atención");
                error.SetError(txtCodFuncionario, "Debe seleccionar o ingresar el Codigo del profesional");

            }
            else
            {
                if (this.isNuevo)
                {

                    //PRIMER INSERT
                    respuesta = negociosCitas.insertar(

                       Convert.ToInt32(this.txtCodPaciente.Text), //ok
                       Convert.ToInt32(this.txtCodFuncionario.Text),
                       Convert.ToInt32(this.txtIDHorario.Text),
                       this.dtpFecha.Value.ToString("yyyy-MM-dd"),
                       Convert.ToString(this.cmbEstado.SelectedItem),
                       this.lblEstadoPago.Text
                        );

                        //RECUPERAR EL ID DE LA CITA INSERTADA
                        this.txtIDCita.Text=

                        //SEGUNDO INSERT
                    /*respuesta = negociosPagos.insertar(
                       Convert.ToInt32(this.lblIDMedioPAGO.Text),
                       Convert.ToInt32(this.txtIDCita.Text), ACA DEBERIA IR EL ULTIMO ID INSERTADO
                       this.dtpFecha.Value.ToString("yyyy-MM-dd H:mm:ss"),
                       Convert.ToDecimal(this.txtMontoPago.Text),
                       this.txtDetallePago.Text);*/

                }
                else
                {
                    respuesta = negociosCitas.editar(
                       Convert.ToInt32(this.txtIDCita.Text),
                       Convert.ToInt32(this.txtCodPaciente.Text), //ok
                       Convert.ToInt32(this.txtCodFuncionario.Text),
                       Convert.ToInt32(this.txtIDHorario.Text),
                       this.dtpFecha.Value.ToString("yyyy-MM-dd"),
                        Convert.ToString(this.cmbEstado.SelectedItem)
                        );
                }

                if (respuesta.Equals("OK"))
                {
                    if (this.isNuevo)
                    {
                        this.mensajeOK("REGISTRO INSERTADO CON EXITO EN LA BASE DE DATOS");
                        //ACA PODRIA LLAMAR A LA ACTUALZIACION DEL ESTADO DE LA CITA YA QUE LA RESPUESTA DEL METODO INSERTAR FUE OK
                        //negociosCitas.editarEstadoPago(Convert.ToInt32(txtIDCita.Text), "Pagado");  

                        this.Hide();
                    }
                    else
                    {
                        this.mensajeOK("REGISTRO ACTUALIZADO CON EXITO");
                    }
                }
                else
                {
                    this.mensajeError(respuesta);
                }

                this.isNuevo = false;
                this.isEditar = false;
                this.botones();
                this.limpiarControles();
                //this.cargarGrilla();
            }

        }
        catch (Exception ex)
        {

            MessageBox.Show(ex.Message + ex.StackTrace);
        }
    }

Greetings to all, I read your comments

    
asked by Nicolas Ezequiel Almonacid 24.08.2018 в 15:52
source

1 answer

2

You should use SELECT LAST_INSERT_ID(); if you want to make sure that you are really getting the value you just inserted. And yes, you could put it directly in the following insert, for example:

INSERT INTO tabla (campo1, campo2, campo3) VALUES ('cosa1', 'cosa2', 'cosa3');
INSERT INTO table2 (campoz, idanterior) VALUES ('campoz', last_insert_id());

Reference in the MySQL manual

    
answered by 24.08.2018 / 16:12
source