开发者

how to escape for mysql in asp.net?

What's the ASP.NET equivalent of this PHP code?

$db = new mysqli(/*some data*/);
$db->query('INSERT INTO `log` (`开发者_运维技巧msg`) VALUES ("'.$db->real_escape_string($_POST['mesg']).'");');

Im only interested in mysqli_real_escape_string, but the only examples I can find on Google for ASP.NET and SQL are all injectable.

So my question is: How do I pass user data to SQL in ASP.NET using ADO.NET?

If you use replace of regex, please base your example on this code.


When using this approach, you'll want to look into using parameterized SQL in your code.

using (SqlConnection connection = new SqlConnection(connectionString))
{
  DataSet userDataset = new DataSet();

  SqlDataAdapter myDataAdapter = new SqlDataAdapter("SELECT * FROM Log WHERE Message = @Message", connection);                

  myCommand.SelectCommand.Parameters.Add("@Message", SqlDbType.VarChar, 11);

  myCommand.SelectCommand.Parameters["@Message"].Value = messageString;

  myDataAdapter.Fill(userDataset);
}


First of all, you should use properties if possible. Then you don't need to escape the strings yourself.

If you can't do that, you need to escape both backslashes and apostrophes:

public static string EscapeForMySQL(string str) {
  return str.Replace("\\", "\\\\").Replace("'", "\\'")
}


If possible please refactor to avoid dynamic sql or use parameterized queries.

Use Parameterized queries for ODBC (I believe in oledbcommand will work here as well)

http://weblogs.asp.net/cumpsd/archive/2004/04/05/107456.aspx

See my talk on it - its the first subject:

http://channel9.msdn.com/Events/TechEd/NorthAmerica/2011/DEV333

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜