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?
or other variation you might try like this
Use my SqlBuilder class. It lets you write paramaterized queries without ever creating a parameter, or having to worry about what its called. Your code will look like this...
Your code will be shorter and much more readable. Compared to concatenated queries, you don't even need extra lines. The class you need is here...
Another technique, you can use..
Add the end you can iterate to insert the parameters in your
command object
Better still, use my shiny new Visual Studio extension. You declare your parameters in your sql, intact in its own file. My extension will run your query when you save your file, and will make you a wrapper class to call at runtime, and a results class to access your results, with intellisense all over da place. You will see your sql parameters as arguments to the Execute() methods of the wrapper class. You will never have to write another line of parameter code in C#, or reader code, or cmd, or even connection (unless you want to manage that yourself). Gone gone gone :-)
Here you go... via dapper:
that maps to
ExecuteNonQuery
, but there are other methods, such asQuery<T>
(binds the data very efficiently by name into objects of typeT
per row),Query
(likeQuery<T>
, but usesdynamic
), and a few others (binding multiple grids or multiple objects, etc). All ridiculously optimized (IL-level meta-programming) to be as fast as possible.Use single line SqlParameterCollection.AddWithValue Method