MySqlCommand Command.Parameters.Add 已过时 [英] MySqlCommand Command.Parameters.Add is obsolete

查看:46
本文介绍了MySqlCommand Command.Parameters.Add 已过时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在 Visual Studio 2010 中制作 C# windows 窗体应用程序.

I'm making an C# windows Form Application in visual studio 2010.

那个应用程序正在连接到一个 mysql 数据库,我想在其中插入数据.

That application is connecting to an mysql database, and I want to insert data in it.

现在我有这部分代码吗:

Now do I have this part of code:

MySqlConnection connection;
string cs = @"server=server ip;userid=username;password=userpass;database=databse";
connection = new MySqlConnection(cs);
connection.Open();

MySqlCommand command = new MySqlCommand();
string SQL = "INSERT INTO `twMCUserDB` (`mc_userName`, `mc_userPass`, `tw_userName`, `tw_userPass`) VALUES ('@mcUserName', '@mcUserPass', '@twUserName', '@twUserPass')";
command.CommandText = SQL;
command.Parameters.Add("@mcUserName", mcUserNameNew);
command.Parameters.Add("@mcUserPass", mcUserPassNew);
command.Parameters.Add("@twUserName", twUserNameNew);
command.Parameters.Add("@twUserPass", twUserPassNew);
command.Connection = connection;
command.ExecuteNonQuery();
connection.Close();

连接正常.那行得通.

我阅读了这里我现在拥有的方式是进行查询的一种保存方式.还是这样吗?

I readed here that the way that I have now, is an save way to do query's. Is that still right?

现在是真正的问题.使用上面的代码,我在 Visual Studio 中收到以下警告:

And now to the real question. With that code above, I get the following warning in visual studio:

'MySql.Data.MySqlClient.MySqlParameterCollection.Add(string, object)' is obsolete: '"Add(String parameterName, Object value) has been deprecated.  Use AddWithValue(String parameterName, Object value)"'

该警告适用于每个参数.添加

That warning is for every parameters.add

它甚至不起作用,因为插入的值是@mcUserName、@mcUserPass 等,而不是变量 mcUserNameNew 等保存的值...

And it isn't even working, because the values that are inserted are @mcUserName, @mcUserPass and so on, instead of the values that the variables mcUserNameNew and so on are holding...

所以我的问题是,我做错了什么,sql注入保存的新方法是什么?

So my question is, am I doing something wrong, and what is the new way to sql injection save do an query?

推荐答案

try AddWithValue

command.Parameters.AddWithValue("@mcUserName", mcUserNameNew);
command.Parameters.AddWithValue("@mcUserPass", mcUserPassNew);
command.Parameters.AddWithValue("@twUserName", twUserNameNew);
command.Parameters.AddWithValue("@twUserPass", twUserPassNew);

并且不要用单引号将占位符括起来.

and don't wrap the placeholders with single quotes.

string SQL = "INSERT INTO `twMCUserDB` (`mc_userName`, `mc_userPass`, `tw_userName`, `tw_userPass`) VALUES (@mcUserName, @mcUserPass, @twUserName, @twUserPass)";

这篇关于MySqlCommand Command.Parameters.Add 已过时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆