我正在使用Visual Studio 2010制作一个C# Windows窗体应用程序。
该应用程序连接到一个MySQL数据库,我希望在其中插入数据。
现在我有了这部分代码:
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();
连接正常,是可行的。
我在这里读到,现在我使用的方式是一个安全的进行查询的方式。这仍然正确吗?
现在来谈谈真正的问题。使用上述代码,在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)"'
这个警告适用于每个parameters.add。
而且它甚至没有起作用,因为插入的值是@mcUserName、@mcUserPass等,而不是变量mcUserNameNew等所持有的值...
所以我的问题是,我做错了什么,新方法如何实现防止SQL注入并执行查询?
AddWithValue
。 - Habib