Can I protect against SQL injection by escaping single-quote and surrounding user input with single-quotes?

后端 未结 18 2266
忘了有多久
忘了有多久 2020-11-22 14:03

I realize that parameterized SQL queries is the optimal way to sanitize user input when building queries that contain user input, but I\'m wondering what is wrong with takin

18条回答
  •  隐瞒了意图╮
    2020-11-22 14:50

    I've used this technique when dealing with 'advanced search' functionality, where building a query from scratch was the only viable answer. (Example: allow the user to search for products based on an unlimited set of constraints on product attributes, displaying columns and their permitted values as GUI controls to reduce the learning threshold for users.)

    In itself it is safe AFAIK. As another answerer pointed out, however, you may also need to deal with backspace escaping (albeit not when passing the query to SQL Server using ADO or ADO.NET, at least -- can't vouch for all databases or technologies).

    The snag is that you really have to be certain which strings contain user input (always potentially malicious), and which strings are valid SQL queries. One of the traps is if you use values from the database -- were those values originally user-supplied? If so, they must also be escaped. My answer is to try to sanitize as late as possible (but no later!), when constructing the SQL query.

    However, in most cases, parameter binding is the way to go -- it's just simpler.

提交回复
热议问题