如何将字符串转换为安全的 SQL 字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5528972/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 10:00:31  来源:igfitidea点击:

How do I convert a string into safe SQL String?

.netsqlsanitization

提问by Diskdrive

I'm generating some sql insert statements from a bunch of text files.

我正在从一堆文本文件中生成一些 sql 插入语句。

These text files are generally user input data. I would like to sanitize this data so that it's not going to break the insert statement.

这些文本文件通常是用户输入的数据。我想清理这些数据,这样它就不会破坏插入语句。

For example, some of the input data, people have used the word Don't. The "'" in don't will lead the sql statement to think the string has ended and therefore cause an error.

比如一些输入数据,人们就用了Don't这个词。don't 中的“'”会导致 sql 语句认为字符串已经结束并因此导致错误。

Is there any .NET method I can call to kind of convert all of these characters to either escape codes or safe characters?

我可以调用任何 .NET 方法来将所有这些字符转换为转义码或安全字符吗?

采纳答案by Michael Stum

Don't sanitize your strings. Use parameterized queries instead, as they handle all sanitization.

不要消毒你的琴弦。改用参数化查询,因为它们处理所有清理。

You don't specify which database you are using, so I assume it is MS SQL Server. Microsoft has an articleon the official ASP.net website about this. Also see MSDN for SqlCommand.Parametersand the AddWithValuemethod.

您没有指定您使用的是哪个数据库,所以我假设它是 MS SQL Server。Microsoft在官方 ASP.net 网站上有一篇关于此的文章。另请参阅 MSDN 以了解SqlCommand.ParametersAddWithValue方法。

回答by Andomar

There is only a single character you have to escape: ansi 0x27, aka the single quote:

您只需要转义一个字符:ansi 0x27,也就是单引号:

safeString = unsafeString.Replace("'","''");