select 语句经典小算法

/*返回按条件的搜索*/
public ResultSet getBookTypeList(Connection con,BookType bookType) throws Exception {
  StringBuffer sb_Sql=new StringBuffer("select * from t_bookType");
  String search_BookTypeName=bookType.getBookTypeName();
  if(StringUtil.isEmpty(search_BookTypeName)==false){
   sb_Sql.append(" and bookTypeName like '%"+search_BookTypeName+"%'");
  }
  PreparedStatement pstmt=con.prepareStatement(sb_Sql.toString().replaceFirst("and","where"));
  return pstmt.executeQuery();
 }
 
对于以上代码,当有多个判断条件时,如下:
 
if(条件1)sb.append(" where bookTypeName ……")

if(条件2)sb.append(" and bookTypeDetail ……")
 
if()…………
 
会有很好的效果。
原文地址:https://www.cnblogs.com/hualidezhuanshen/p/3130984.html