mysql查询小技巧

如果所传bookTypeName为空则执行select * from t_bookType(搜索框里未输入信息)

否则追加 and bookTypeName like  '%"+bookType.getBookTypeName()+"%'

如果是追加的第一个and则替换为where:

sb.toString().replaceFirst("and", "where")

方法代码示例如下:

public ResultSet bookTypeList(Connection con,BookType bookType) throws SQLException{
StringBuffer sb=new StringBuffer("select * from t_bookType") ;
if(StringUtil.isNotEmpty(bookType.getBookTypeName())){
sb.append(" and bookTypeName like '%"+bookType.getBookTypeName()+"%'");
}
PreparedStatement pstmt=con.prepareStatement(sb.toString().replaceFirst("and", "where"));
return pstmt.executeQuery();
}

 

posted @ 2018-03-17 19:09  SnowsF  阅读(175)  评论(0编辑  收藏  举报