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;
}