2

Let's say I have the below code (stripping out useless things like the connection string, dataset creation, setting the command type etc).

string sql = "SELECT * FROM SomeTable WHERE Field=@ParamValue";

using (SqlConnection conn = new SqlConnection())
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
    cmd.Parameters.Add(new SqlParameter("ParamValue", someValue));
    da.Fill(ds);
}

Is this use of a parameterized query sufficient to ensure security against SQL injection, or do I need to strip quotes from someValue first, before passing it in as a parameter?

Jon Story
  • 2,881
  • 2
  • 25
  • 41

1 Answers1

4

No, you do not need to escape quotes. When you perform a SQLCommand using SQLParameters, the parameters are never inserted directly into the statement.

Instead, a system stored procedure called sp_executesql is called and given the SQL string and the array of parameters (the TDS protocol).

The parameters are isolated and treated as data. This mitigates SQL injection concerns and provides other benefits, such as strong-typing and improved performance.

Antoine V
  • 6,998
  • 2
  • 11
  • 34