标签:nts class size state 分页查询 pageinfo stack param str
public List<User> getUserByPage(PageInfo pif,User user){ List<User> lu = new ArrayList<User>(); Connection conn = DButil.getconn(); String sql = "SELECT u.uname,u.uaddr from userinfo u "; // !"".equals(user.getUname()) 如果前段搜索用户名不填写,传到后端的是空值 boolean contactAnd = false; String myWhere = "where"; String myAnd = "and"; List<String> params = new ArrayList<>(); if(user.getUname()!=null&&!"".equals(user.getUname())) { if(contactAnd) { sql += myAnd + " uname = ? "; }else { sql += myWhere + " uname = ? "; contactAnd = true; } params.add(user.getUname()); } if(user.getUaddr()!=null&&!"".equals(user.getUaddr())) { if(contactAnd) { sql += myAnd + " uaddr like ? "; }else { sql += myWhere + " uaddr like ? "; contactAnd = true; } params.add("%"+user.getUaddr()+"%"); } // 拼接分页查询的limit sql+= " Limit "+(pif.getPage()-1)*pif.getPageSize() +","+pif.getPageSize(); try { PreparedStatement ps = conn.prepareStatement(sql); // 占位符个数不确定,所以不能直接.所以需要对是否有占位符有几个进行判断 // 如果有拼接占位符号?,则在循环中对占位符进行赋值 for(int i = 0;i<params.size();i++) { ps.setString(i+1,params.get(i)); } ResultSet rs = ps.executeQuery(); while(rs.next()) { User user1 = new User(); user1.setUname(rs.getString("uname")); user1.setUaddr(rs.getString("uaddr")); lu.add(user1); } System.out.println(lu); } catch (SQLException e) { e.printStackTrace(); } return lu; }
标签:nts class size state 分页查询 pageinfo stack param str
原文地址:https://www.cnblogs.com/klory/p/10775529.html