我需要创建一个字符串方法,它接受一个字符串并将其转义,以便它可以在数据库SQL查询中使用,例如:
"This is john's dog" ==> "This is john''s dog"
"This is a 'quoted' string" ==> "This is a ''quoted'' string"
Run Code Online (Sandbox Code Playgroud)
我希望我的方法看起来像这样:
string PrepareForSQLCommand(string text)
{
...
}
Run Code Online (Sandbox Code Playgroud)
无论如何,我不知道需要在SQL查询中转义的所有字符.我不确定这样做的最佳方法是什么,或者在C#中是否存在一些现有的强大内置函数.
抱歉没有提到这个:我没有选择使用参数化的查询.
摊晒
通常的方法是使用参数化查询作为SqlCommand的一部分.
SqlCommand command = new SqlCommand("SELECT * FROM MyTable WHERE MyCol = @param", connection);
command.Parameters.AddWithValue("@param", "This is john's dog");
Run Code Online (Sandbox Code Playgroud)
然后,该框架确保您的安全,这比尝试自己解决所有可能的注入攻击更不容易出错.
| 归档时间: |
|
| 查看次数: |
1895 次 |
| 最近记录: |