Java数据库学习之SQL语句动态拼接
public class UserDaoImpl implements UserDao { @Override public List<User> getUserByPage(PageInfo pif,User user){ List<User> lu = new ArrayList<User>(); Connection conn = DButil.getconn(); // 注意拼接式字符串之间要有空格 userinfo u " 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) { // " 空格 uname = ?空格 " 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; }