Sanitize table/column name in Dynamic SQL in .NET? (Prevent SQL injection attacks)

前端 未结 3 1097
误落风尘
误落风尘 2020-11-29 12:34

I am generating some Dynamic SQL and would like to ensure that my code is safe from SQL injection.

For sake of argument here is a minimal example of how it is genera

3条回答
  •  攒了一身酷
    2020-11-29 13:00

    For SQL Server, it's pretty simple to sanitize an identifier:

    // To make a string safe to use as an SQL identifier :
    // 1. Escape single closing bracket with double closing bracket
    // 2. Wrap in square brackets
    string.Format("[{0}]", identifier.Replace("]", "]]"));
    

    Once wrapped in brackets and escaped, the only thing that won't work as an identifier is an empty/null string.

提交回复
热议问题