Search code examples
c#mysqlasp.net-mvcparameterized-query

c# mysql insert statement. Parameterized query example?


I'm trying to get this insert statement to work.

string sql = "INSERT INTO usuario (apellido,nombre,email,password,id_localidad) "
                         + "VALUES (?apellido,?nombre,?email,?password,?idLocalidad); ";

            MySqlCommand cmd = new MySqlCommand(sql, conn);
            cmd.Prepare();
            cmd.Parameters.AddWithValue("apellido ", usuario.apellido);
            cmd.Parameters.AddWithValue("nombre ", usuario.nombre);
            cmd.Parameters.AddWithValue("email ", usuario.email);
            cmd.Parameters.AddWithValue("password ", password);
            cmd.Parameters.AddWithValue("idLocalidad ", usuario.localidad.idLocalidad);
cmd.ExecuteNonQuery();

but yet again, i get an exception saying first parameter needs to be defined. If I use the @ placeholder, i get a null error when clearly I'm adding parameters. I also added the following to my connection string.

AllowUserVariables=True

I know variants of this question have appeared throughout the site, but I have followed advice provided and still haven't been able to make it work.

Any help will be greatly appreciated. Thanks


Solution

  • You could try to specify MySQLDbType to match your DB Type and use Add function:

    cmd.Parameters.Add("?apellido", MySqlDbType.VarChar).Value = usuario.apellido;