Benefits of use parameters instead of concatenation

人走茶凉 提交于 2019-11-29 15:23:12
  • Safety. Concatenation opens you up to SQL-injection, especially when TB stands for Textbox. (Obligatory XKCD cartoon)
  • Type safety. You solve a lot of DateTime and number formatting issues.
  • Speed. The query does not change all the time, the system(s) may be able to re-use a query handle.

Advantages

SQL Injection avoidance is the main one. It ensures a complete separation of user supplied data and executable code.

It also means that your application will work correctly when people innocently search for phrases like O'Brien without you needing to manually escape all these search terms.

Using datetime parameters for example avoids issues with ambiguous date formats in string representations.

If SQL Server it means better use of the plan cache. Rather than having loads of similar adhoc queries compiled and stored it just has one that is reused.

Disadvantages

None:

You may occasionally encounter parameter sniffing issues due to inappropriate re-use of a plan but that doesn't mean that you should not use parameterised queries in this event. In SQL Server you would typically add a RECOMPILE or OPTIMIZE FOR query hint to avoid this issue.

One very good reason is to prevent SQL injection.

Imagine if your usernameTB.Text was equal to:

"'some  text', 'password') GO; DROP TABLE [USER DATA] GO;"

If you use parameter this string will be escaped correctly (e.g. ' replaced with ''), so it will become the value of the field.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!