validate existence before inserting (c #)

0

Hello good afternoon everyone, guys consult, I need that when wanting to insert a new record, before validating if a certain field already exists in the database, for this I have a procedure stored in mysql, I try it in workbench and I it works, now in C # I'm doing a method in which I pass the parameter to look for, but it throws me the following error: "YOU CAN NOT CONVERT THE TYPE BOOL IN STRING IMPLICITLY".

I work with a layered model, in my data layer I have the method in question:

 public string validarExistencia(datosFuncionario funcionario)
    {
        //string respuesta = "";
        MySqlConnection con = new MySqlConnection();

        try
        {
            //CADENA DE CONEXION
            con.ConnectionString = conexion.cadenaConexion;

            //ABRIMOS LA CONEXION
            con.Open();

            //COMANDO PARA EJECUTAR CONSULTA
            MySqlCommand cmd = new MySqlCommand();
            cmd.Connection = con;

            //LLAMAMOS A LA CONSULTA O PROCEDIMIENTO ALMACENADO
            cmd.CommandText = "spValidaExistFuncionario";
            cmd.CommandType = CommandType.StoredProcedure;

            //ID AUTOINCREMENTAL
            MySqlParameter parIdFunc = new MySqlParameter();
            parIdFunc.ParameterName = "@rut1";
            parIdFunc.MySqlDbType = MySqlDbType.VarChar;
            parIdFunc.Size = 25;
            parIdFunc.Value = funcionario.Rut;
            cmd.Parameters.Add(parIdFunc);

            //EJECUCION DEL COMANDO
            int respuesta = Convert.ToInt32(cmd.ExecuteScalar());

            return respuesta == 0;

        }
        catch (Exception ex)
        {

            //respuesta = ex.Message;
        }

        //CIERRE DE CONEXION
        finally
        {
            if (con.State == ConnectionState.Open) con.Close();
        }

        //RETORNAMOS LA VARIABLE DEL METODO
        //return respuesta;
    }

and my stored procedure is like this:

CREATE DEFINER='administrador'@'%' PROCEDURE 'spValidaExistFuncionario'(in rut1 varchar(25))
    BEGIN
    SELECT COUNT(*) FROM funcionario WHERE rut = rut1; 

    END

and my save button:

        try
        {
            string respuesta = "";

            //validamos los campos obligatorios
            if (this.txtDocumento.Text == string.Empty)
            {
                mensajeError("Faltan datos por ingresar, favor verificar");
                error.SetError(txtDocumento, "Debe Ingresar Numero de Documento");
            }
            else
            {
                if (this.isNuevo)
                {
                   respuesta = negociosFuncionario.insertar(
                   this.txtDocumento.Text,
                   this.txtNombres.Text,
                   this.txtApePat.Text,
                   this.txtApeMat.Text,
                   this.dtpFechaNac.Value.ToString("yyyy-MM-dd H:mm:ss"),
                   this.cmbSexo.Text,
                   this.txtDireccion.Text,
                   Convert.ToInt32(this.txtFono.Text),
                   this.txtCorreo.Text,
                   this.cmbPrevSalud.Text,
                   this.cmbPrevSocial.Text,
                   this.txtComentarios.Text
                  );
                }
                else
                {
                   respuesta = negociosFuncionario.editar(
                   Convert.ToInt32(this.txtCodFuncionario.Text),
                   this.txtDocumento.Text,
                   this.txtNombres.Text,
                   this.txtApePat.Text,
                   this.txtApeMat.Text,
                   this.dtpFechaNac.Value.ToString("yyyy-MM-dd H:mm:ss"),
                   this.cmbSexo.Text,
                   this.txtDireccion.Text,
                   Convert.ToInt32(this.txtFono.Text),
                   this.txtCorreo.Text,
                   this.cmbPrevSalud.Text,
                   this.cmbPrevSocial.Text,
                   this.txtComentarios.Text
                  );

                }

                if (respuesta.Equals("OK"))
                {
                    if (this.isNuevo)
                    {
                        this.mensajeOK("REGISTRO INSERTADO CON EXITO EN LA BASE DE DATOS");
                    }
                    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, have a great day.

    
asked by Nicolas Ezequiel Almonacid 27.07.2018 в 21:17
source

1 answer

0

Change the following line of code:

 return respuesta == 0;

By:

return respuesta.ToString();

Explanation:

Your function is defined to return a data of type string :

public string validarExistencia(datosFuncionario funcionario)
{

Your result variable is of type Int, however the following line of code is a comparison therefore returns a bool type:

  return respuesta == 0;

Use the ToString () method to convert it to the same data type. You could also change the data type of your function to int if it suits you.

Note:

If with the aforementioned instruction you want to return the zero value in the event that the result is null you can use the following code:

        object obj = cmd.ExecuteScalar();
        int respuesta = ((obj==DBNull.Value)? 0: Convert.ToInt32(obj));
    
answered by 27.07.2018 / 22:35
source