mysql_real_escape_string() in .NET Framework

2019-08-01 07:48发布

问题:

i want to find a function in .NET framework to calls SQL-Server's library for escaping really a value for sending to sql server, as mysql-real-escape-string() calls MySQL's library to do in PHP.
please propose a method that i can call it and it return escaped string via one round-trip to database, no need fo executing It's query
Is there it?

回答1:

Why do you want to do that? The correct way to send user input to the database is not to escape it, but to use query parameters.

using(var command = new SqlCommand("insert into MyTable(X, Y) values(@x, @y)", connection))
{
    command.Parameters.Add("@x", textBoxX.Text);
    command.Parameters.Add("@y", textBoxY.Text);
    command.ExecuteNonQuery();
}

This provides better performance, because the query text is always the same so the query execution plan can be cached. This also protects you against SQL injection attacks. And it also allows you to ignore data formatting issues (e.g. how is a DateTime formatted in SQL-Server? How should you represent a number in SQL? and so on)