我有一个存储在列表中的关键字列表。
要从表中获取记录,请使用以下查询:
sqlBuilder.Append("SELECT name, memberid FROM members WHERE"); StringBuilder sqlBuilder = new StringBuilder(); foreach (string item in keywords) { sqlBuilder.AppendFormat(" LOWER(Name) LIKE '%{0}%' AND", item); } string sql = sqlBuilder.ToString();
您可能已经注意到,我的查询容易受到sql注入的攻击,因此我想通过SqlCommand()使用参数。我已经尝试了以下方法,但仍然无法正常工作:
foreach (string item in keywords) { sqlBuilder.AppendFormat(" LOWER(Name) LIKE '%' + @searchitem + '%' AND", item); SqlCommand cmd = new SqlCommand(sqlBuilder.ToString()); cmd.Parameters.AddWithValue("@searchitem",item); }
我在哪里犯错,或者应该怎么做?
您在这里做错了几件事:
@searchitem
CommandText
AND
改进建议(本质上没有错,但也不是最佳实践):
%
LOWER
代码示例:
SqlCommand cmd = new SqlCommand(); StringBuilder sqlBuilder = new StringBuilder(); sqlBuilder.Append("SELECT name, memberid FROM members "); var i = 1; foreach (string item in keywords) { sqlBuilder.Append(i == 1 ? " WHERE " : " AND "); var paramName = "@searchitem" + i.ToString(); sqlBuilder.AppendFormat(" Name LIKE {0} ", paramName); cmd.Parameters.AddWithValue(paramName, "%" + item + "%"); i++; } cmd.CommandText = sqlBuilder.ToString();