Juan M Juan M - 1 year ago 66
SQL Question

c# mysql insert statement. Parameterized query example?

I'm trying to get this

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.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);

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


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

Answer Source

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

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