[英]c# mysql insert statement. Parameterized query example?
I'm trying to get this insert
statement to work. 我正在尝试使此
insert
语句起作用。
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. 如果我使用
@
占位符,则很明显在添加参数时会出现null
错误。 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
谢谢
您可以尝试指定MySQLDbType
以匹配您的数据库类型并使用Add
函数:
cmd.Parameters.Add("?apellido", MySqlDbType.VarChar).Value = usuario.apellido;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.