Possible Duplicate:
XKCD SQL injection — please explain
I’m very new in C# and I want to know.
When building an SQL string in C#, why do we need to use an SqlParameter object to represent user’s input instead of directly passing in the string?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I’m assuming you mean why it’s better to write:
rather than
The latter form has three problems:
It allows SQL Injection Attacks unless you’re very careful about escaping – which the code above isn’t. Imagine what the SQL would look like if the user put input of:
It mixes code and data. You can’t see a clean representation of what you’re trying to do, whereas the first form shows which bits are fixed and which are variable input
While not a problem for strings so much, parameters avoid unnecessary data conversions. For example, when using a date or date/time value, with the second approach you end up needing to worry about which text formats the database will accept, even though you’ve started with a
DateTimevalue (say) and the database will end up with a value of some appropriate date/time type. Going via a string representation causes nothing but trouble.Additionally, in some situations the first approach may improve performance, allowing the database to cache a query execution plan. There’s quite a lot of nuance around that though, and it’s quite database-specific.