C# 用字符串中的两个单引号替换所有单引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13277517/
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
Replace all single quotes with two single quotes in a string
提问by SKJ
I am trying to read value from DB using c#. The query string contains multiple single quotes - such as: Esca'pes' (the query strings are being read from a text file)
我正在尝试使用 c# 从数据库读取值。查询字符串包含多个单引号 - 例如:Esca'pes'(正在从文本文件中读取查询字符串)
So, I wanted to replace all the single quotes with two single quotes before forming the SQL query. My code is as below:
所以,我想在形成 SQL 查询之前用两个单引号替换所有单引号。我的代码如下:
if (name.Contains('\''))
{
name = name.Replace('\'','\''');
}
How to fix this?
如何解决这个问题?
采纳答案by Dai
Use strings, not char literals.
使用字符串,而不是字符文字。
name = name.Replace("'", "''");
However it sounds like you're concatenating SQL strings together. This is a huge "DO NOT" rule in modern application design because of the risk of SQL injection. Please use SQL parameters instead. Every modern DBMS platform supports them, including ADO.NET with SQL Server and MySQL, even Access supports them.
但是,这听起来像是将 SQL 字符串连接在一起。由于 SQL 注入的风险,这是现代应用程序设计中的一个巨大的“不要”规则。请改用 SQL 参数。每个现代 DBMS 平台都支持它们,包括带有 SQL Server 和 MySQL 的 ADO.NET,甚至 Access 也支持它们。
回答by Tyler Lee
Since you want to replace a single character with two characters, you need to use the String overload of Replace
由于要将单个字符替换为两个字符,因此需要使用 Replace 的 String 重载
if (name.Contains('\''))
{
name = name.Replace("'","''");
}
(Note: single quotes don't require escaping in Strings like they do in character notation.)
(注意:单引号不需要像在字符符号中那样在字符串中转义。)
回答by Brook
name = name.Replace("'","''");
name = name.Replace("'","''");
On an unrelated note, you're concatenating strings for use in SQL? Try parameters instead, that's what they're meant for. You're probably making it harder than it needs to be.
在一个不相关的注释中,您正在连接字符串以在 SQL 中使用?尝试使用参数,这就是它们的用途。你可能让它变得比需要的更难。

