首页 > 其他 > 详细

黑马视频-多条件搜索

时间:2015-11-14 19:12:59      阅读:176      评论:0      收藏:0      [点我收藏+]
  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());
模糊查询 


























黑马视频-多条件搜索

原文:http://www.cnblogs.com/wupd2014/p/4964814.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!