SQL语句,查询条件,如何高效的拼接SQL字符串我有0-4个条件,运算关系是AND ,每一个条件都是可有可无的,所以 where  和 and 关键字 也是灵活的, 这种情况下,
如何写一个高效的 函数 ,把SQL条件那块拼接出来 。请大大们教教!

解决方案 »

  1.   

    预编译语句 
    如 StringBuilder sb="select * from tb1 where 1=1"
    if(userName!=null&&!"".equals(userName)){sb.append(" and userName=?")}
    这样的话 你底层就要设计好了!因为参数是动态的
      

  2.   

     if(address==null) return -10;
      if(email==null) return -10; 
      if(ip==null) return -10;
      
      String sql = "select * from LY_ZILIAO where  ziliao_id!= '"+id+" 'and( address='" + address.trim() +
          "'or EMAIL='" + email.trim() + "'or ip='" + ip.trim() + "'";
           if (telephone != null && telephone.length() > 1) {
            sql += " or TELEPHONE='" + telephone.trim() + "'";
           }
          if (mobile != null && mobile.length() > 1) {
           sql += " or mobile='" + mobile.trim() + "'";
          }
           sql +=")";
      

  3.   


    这样的?用list存储那0-4个条件String getCondition(List conditions){
      String condition = "where 1=1";
      for(int i = 0; i < conditions.size(); i++){
         String temp = (String)conditions.get(i);
         condition += " and ";
         condition += temp 
      }
      return condition; 
    }
      

  4.   

    同意2楼,不管有没有条件,都加上where ,对效率应该不会有影响
      

  5.   

    拼接好累哦 用 PreparedStatement算了