Search code examples
c#asp.netsqlparameterized

parameterized sql query - asp.net / c#


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?


Solution

  • Use single line SqlParameterCollection.AddWithValue Method

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