How does SqlCommand sanitize parameters?

2019-02-12 15:07发布

Using SqlParameters is a recommended method to prevent SQL Injection in your database queries. Where can I find the code/function that internally sanitizes these parameters? I'd like to re-use this function in a custom implementation of mine. I tried to find it using Reflector, but was unsuccessful.

1条回答
仙女界的扛把子
2楼-- · 2019-02-12 15:37

It protects against SQL Injection, not XSS, and there is no code or function that sanitizes the parameter data.

The protection is accomplished by transmitting the parameter values to the server separately from the query string, so that the values are never substituted directly into the sql statement.

So instead of sql server running something like this:

SELECT * FROM [table] WHERE [column] = ParameterValue

It's more as if it ran something like this:

DECLARE @ParamValue int
  -- //@ParamValue variable is populated from the framework in a safe way
SELECT * FROM [table] WHERE [column] = @ParamValue

This is faster and much more secure and robust than a function that would have to evaluate the parameter data. Such a function would need to be very complex (read: error prone) to handle things like custom escape characters and future enhancements.

This neatly side steps the whole issue: data is data, code is code, and never the twain shall meet.


Your comment to the other, now deleted, answer:

If I pass in the value O'Rourke, it encodes it to be O''Rourke so that it doesn't break the query. Correct?

No, that is not correct. The variable is created directly from a data block, and so no special escaping or encoding is needed.

查看更多
登录 后发表回答