SqlCommand and AddWithValue – The Proper Way Of Adding Parameters To SQL Queries

When adding parameters to SQL queries in code behind ASP.NET pages, the ideal syntax is to use a SQL parameter to help build your query string, rather than creating a text string on the fly.

Example (Bad usage of inline substitution)

mySqlCommand = new SqlCommand("SELECT * FROM [PollAnswers] WHERE ([PollID] = '" + PollID + "') ORDER BY [SortOrder]", mySqlConnection);

Instead use Parameters.AddWithValue and substitute the values in place.

 mySqlCommand = new SqlCommand("SELECT * FROM [PollAnswers] WHERE ([PollID] = @PollID) ORDER BY [SortOrder]", mySqlConnection);

mySqlCommand.Parameters.AddWithValue("@PollID", PollID);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s