黑马视频-多条件搜索

  1. StringBuild sql=new StringBuild("select * from tb where 1=1")
  2. if(name!=""){
  3. sql.Append("and name like '%"+name+"%'");
  4. }
  5. if(sex!=""){
  6. sql.Append("and sex like '%"+sex +"%'");
  7. }


但是1=1对于某些数据库来说,会造成性能下降 ,改进方法如下:
  1. List<string> wheres=new List<string>();
  2. if(name!=""){
  3. wheres.Add(" name like '%"+name+"%'");
  4. }
  5. if(sex!=""){
  6. wheres.Add(" sex like '%"+sex +"%'");
  7. }
  8. ...
  9. if(wheres.count>0){
  10. string wh=string.Join(" and " wheres.ToArray());
  11. sql.Append("where " +wh);
  12. }
多条件查询,使用List集合进行拼接条件 


带参数的SQL语句
  1. List<string> wheres=new List<string>(); //条件字符串
  2. List<SqlParameter> listParameters=new List<SqlParameter>(); //条件参数
  3. if(name!=""){
  4. wheres.Add(" name =@name");
  5. listParameters.Add(new SqlParameter("@name",name))
  6. }
  7. if(sex!=""){
  8. wheres.Add(" sex =@sex");
  9. listParameters.Add(new SqlParameter("@sex",sex))
  10. }
  11. ...
  12. if(wheres.count>0){
  13. string wh=string.Join(" and " wheres.ToArray());
  14. sql.Append("where " +wh);
  15. }
  16. //传入参数
  17. SqlHelper.ExectueDataTable(sql.ToString(),listParameters.ToAray());
模糊查询 


























原文地址:https://www.cnblogs.com/wupd2014/p/4964814.html