Saturday, July 25, 2009

Paramaterized Queries.

Parameterized queries prohibit the sql injection in your web application.
It allows you to safely write code like the following:

Let say, I have a SqlDataReader function to get the details of the particular ID:

public static SqlDataReader GetDetail(int id)
{

string sql = "select * from Raj_table where id = @id ";

SqlParameter paramUserId = new SqlParameter("id", SqlDbType.Int);
paramUserId.Value = id;

// I like to use the SqlHelper class
return SqlHelper.ExecuteReader(GetConnectionString(), CommandType.Text, sql, paramUserId);

}

Firstly, this parameter ensures that the paramater is an INT so a string value would throw an exception here. Also, if we were using a VARCHAR parameter, the SqlParameter value assignment automatically escapes the string for us.

If you run SQL Profiler and observe the queries, you'll notice that they are actually execute via a Stored Procedure (sp_executesql)

Happy Programming!!

No comments:

Post a Comment

Highly Appreciated your comments