2

所以我有一个经销商名称列表,我正在我的数据表中搜索它们——问题是,一些傻瓜必须被命名为“Young's”——这会导致错误。

drs = dtDealers.Select("DealerName = '" + dealerName + "'");

所以我尝试替换字符串(虽然它对我不起作用 - 也许我不知道如何使用替换......)

 DataRow[] drs;
                if (dealerName.Contains("'"))
                {
                    string dealerSearch = dealerName;
                    dealerSearch = dealerSearch.Replace("'", "\'");
                    drs = dtDealers.Select("DealerName = '" + dealerSearch + "'");
                }
                else
                {
                    drs = dtDealers.Select("DealerName = '" + dealerName + "'");
                }

有人有什么好主意吗?

谢谢!托德

4

6 回答 6

10

我通常使用双单引号来表示一个,即

DealerName = 'Young''s'

试试看

于 2011-06-03T00:16:44.253 回答
4

You can use the @ operator called the verbatim operator which means literal in latin. It will not do any interpretation of the characters within the string that would otherwise mean something.

于 2011-06-03T00:20:06.087 回答
3

最终,您可能要考虑使用参数化查询。这将解决您的问题以及您可能尚未想到的其他问题。我发现这个链接详细说明了原因和方式。

于 2011-06-03T00:19:32.990 回答
2

The double-single quote will fix the problem, but an extra note: Your "else" block is redundant.

You could accomplish the same thing by doing this:

 DataRow[] drs;
                if (dealerName.Contains("'"))
                {
                    string dealerSearch = dealerName;
                    dealerSearch = dealerSearch.Replace("'", "''");
                }
                drs = dtDealers.Select("DealerName = '" + dealerName + "'");
于 2011-06-03T00:27:45.150 回答
1
drs = dtDealers.Select("DealerName = '" + dealerName.Replace("'", "\\'") + "'");
于 2011-06-03T00:32:08.780 回答
0

您需要转义\: dealerSearch.Replace("'", "\\'") (或使用@文字)

\被视为 C# 转义,不会出现在实际字符串中。

于 2011-06-03T00:14:15.980 回答