防sql注入之模糊匹配中%、_处理:
StringBuilder sbSql = new StringBuilder(); sbSql.Append(@"SELECT * from tablename t where 1 = 1 "); string name = dictparameters["Name"].ToString(); //Name参数值 if(name.Contains("%") || name.Contains("_")) { name = name.Replace("%", "/%").Replace("_", "/_"); sbSql.AppendFormat(@" AND t.Name like '%{0}%' ESCAPE '/'", name); } else { sbSql.AppendFormat(@" AND t.Name like '%{0}%'", name); }
上述采用的是拼接字符串,现改为参数化,防止sql注入:
StringBuilder sbSql = new StringBuilder(); sbSql.Append(@"SELECT * from tablename t where 1 = 1 "); string name = dictparameters["Name"].ToString(); //Name参数值 if (name.Contains("%") || name.Contains("_")) { name = name.Replace("%", "/%").Replace("_", "/_"); sbSql.Append(@" AND t.Name like '%' + @Name+ '%' + ESCAPE '/'"); } else { sbSql.Append(@" AND t.Name like '%' + @Name+ '%'"); }