我有一个 c#我在其中调用 MySQL 查询的项目,该查询是根据我发送给该方法的字符串构建的。
如果字符串有单引号'
我想用 \'
替换它,这样它对 MySQL 是安全的
但是当我构建查询时,我在字符串的开头和结尾添加了一个单引号和一个 %
;例如 '%texthere%'
所以我需要知道如何替换除第一个和最后一个引号外的每个单引号?
所以它只会替换来自:'%thi'stext%'
为此:'%thi\'stext'%
最佳答案
简单:
int first = s.IndexOf('\'');
int last = s.LastIndexOf('\'');
string prefix = s.Substring(0, first+1);
string query = s.Substring(first+1, last-first-1);
string suffix = s.Substring(last);
s = prefix + query.Replace("'", "\\'") + suffix;
当然,您真的应该改用 SQL 参数。
关于c# - string.replace 每个 ' 除了第一个和最后一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15150154/