What SqlCommand.Parameters.AddWithValue really does?

旧巷老猫 提交于 2019-12-12 16:18:52

问题


What changes SqlCommand.Parameters.AddWithValue() does with the query?

I expect that:

  1. It replaces every ' character by '',

  2. If a parameter value is a string or something which must be converted to a string, it surrounds the value by ', so for example select * from A where B = @hello will give select * from A where B = 'hello world'.

  3. If a parameter value is something "safe" like an integer, it is inserted in a query as is, without quotes, so select * from A where B = @one would give select * from A where B = 1.

Is there any other changes I'm not aware of?


回答1:


The ADO.NET SqlClient driver will not do any replacements! That's a common misconception - it avoids the trouble of replacing anything.

What it does is pass your query with the parameters @param1 ... @paramN straight to SQL Server, along with a collection of parameter name/value pairs. SQL Server then executes those using the sp_executesql stored proc.

No replacements are ever done, there's no "stringing together the complete SQL statement" on the client side - nothing like that. If that's what the ADO.NET runtime were doing, it, too, would be very susceptible to SQL injection attacks.




回答2:


The short answer is that using it adds a value to the end of the SqlParameterCollection, while making your parameter value safe from SQL Injection.

The MSDN documentation does not document the method's exact internal behaviors, and I doubt that it does what you describe. However, if you wish, you can view the source code for the method using Reflector and see exactly what it does.



来源:https://stackoverflow.com/questions/3243194/what-sqlcommand-parameters-addwithvalue-really-does

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