I was told that if using SqlCommand in C# and if you were to add parameters to that command, that it will add security since it will protect against Sql Injection. I was wondering if this is in fact true. If so, how can it stop Sql Injection because it is my understanding that when using parameters, it just inserts a string at a point in the Sql command. So that string could be anything, making Sql Injection possible, correct?
1 Answer
It is not a simple replace. The framework will escape send the values, (especially strings), [as a separate part of the RPC call] so that it is impossible for a value to be executed as code.
Thanks to @PanagiotisKanavos for the correction (6 years later).
5 Comments
Eric R.
Ok, so the framework will remove numbers or anything inside of tick marks ''?
Valamas
No, it will include the tick marks as part of the query. So if your field is a number and there is something like this. ' + 0=0', that whole thing will be the parameter and the query will error as opposed to the injection intention which was to modify the query. An error is what you would want.
Nikola Radosavljević
No, it won't remove anything, it will just encode it so it can be stored in database as it's written. SqlParameter also takes care about type of data which matching column stores and encodes it appropriately, as well as checking bound conditions like if string will fit into column holding VARCHAR(n).
Panagiotis Kanavos
The framework doesn't escape, convert or encode anything. The parameter values are sent as separate fields in the RPC call. They are never part of the query string, never even converted to strings, which is why they can't be executed
harpo
Thanks, @PanagiotisKanavos, answer updated. I did not know that at the time.