Problem with MySQL and Visual Studio [error when adding to table] specifically ExecuteNonQuery ();

0

The error appears on line 43 when trying to insert data. Specifically where it says int filasafectadas = cmd.ExecuteNonQuery(); Here I leave all the code.

  

MySql.Data.MySqlClient.MySqlException: 'Column count does not match   value count at row 1 '

    public bool Insertar(string nombre, string contraseña, string segundo_nombre, string apellido, string sexo, string Tipo_Documento, string Numero_Documento, string Fecha_Nacimiento, string Telefono, string Telefono_dos, string email, string email_dos)
    {
        conexion.Open();

        MySqlCommand cmd = new MySqlCommand(string.Format("insert into usuario values ({0}, '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}', '{8}', '{9}', '{10}', '{11}')", new string[] {nombre, contraseña, segundo_nombre, apellido, sexo, Tipo_Documento, Numero_Documento, Fecha_Nacimiento, Telefono, Telefono_dos, email, email_dos }), conexion);
        int filasafectadas = cmd.ExecuteNonQuery();

        conexion.Close();

        if (filasafectadas > 0) return true;
        else return false;
    }
    
asked by Jatniel Nuñez 05.10.2018 в 03:33
source

1 answer

2

You should use parameters in insert , NEVER be concatenated in string , also when there are so many parameters in a method you should define a class

public class Usuario
{
    public string nombre {get;set;}
    public string contraseña {get;set;}
    public string segundo_nombre {get;set;}

    //resto
}

then your code would be

public bool Insertar(Usuario usuario)
{
    conexion.Open();

    string query = @"insert into usuario (nombrecampo1, nombrecampo2, nombrecampo3, ....") 
                        values ( ?nombre, ?password, ?segundonombre, ...)


    MySqlCommand cmd = new MySqlCommand(query, conexion);
    cmd.Parameters.AddWithValue("?nombre", usuario.nombre);
    cmd.Parameters.AddWithValue("?password", usuario.contraseña);
    cmd.Parameters.AddWithValue("?segundonombre", usuario.segundo_nombre);


    int filasafectadas = cmd.ExecuteNonQuery();

    conexion.Close();

    return filasafectadas > 0;
}

As you will see it is much more neat and understandable to analyze

where I put ... you must complete the rest

    
answered by 05.10.2018 в 06:17