parameterized sql query - asp.net / c#

Mana picture Mana · Nov 28, 2012 · Viewed 7.3k times · Source

So I recently learned that I should absolutely be using parametrized query's to avoid security issues such as SQL injection. That's all fine and all, I got it working.

This code shows some of the code how I do it:

param1 = new SqlParameter();
param1.ParameterName = "@username";
param1.Value = username.Text;
cmd = new SqlCommand(str, sqlConn);
cmd.Parameters.Add(param1);

//and so on

But the problem is, I have over 14 variables that needs to be saved to the db, it's like a registration form. And it would look really messy if I have to write those lines 14 times to parametrize each variable. Is there a more dynamic way of doing this? Like using a for loop or something and parametrizing every variable in the loop somehow?

Answer

Habib picture Habib · Nov 28, 2012

Use single line SqlParameterCollection.AddWithValue Method

cmd.Parameters.AddWithValue("@username",username.Text);