用户管理系统(二)

由于细节比较多,捡重要的随便聊一聊

//查询所有用户信息
public List<Customer> findAll (){
    try {
        String sql="Select * from t_customer";
        return  qr.query(sql, new BeanListHandler<Customer>(Customer.class));
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
//编辑用户信息
public void  edit (Customer c){
    //首先创建sql模板
    try {
        String sql = "update t_customer set cname=?,gender=?,birthday=?," +
                "cellphone=?,email=?,description=? where cid=?";
        Object[] param={c.getCname(),c.getGender(),c.getBirthday(),c.getCellphone(),c.getEmail(),c.getDescription(),c.getCid()};
        qr.update(sql, param);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}

//实现加载客户
public Customer load (String cid){
    //首先需要根据cid在数据库找到用户
    //创建Sql模板
    String sql="select * from t_customer where cid=?";
    //调用qr的query方法
    try {
        return  qr.query(sql, new BeanHandler<Customer>(Customer.class),cid);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }

根据前面提到的,搭建出findAll,edit,load方法,findAll用来查询数据库中所有的记录,edit用来对数据库内容进行修改,load方法用来根据cid加载出用户信息,在后面用户信息预载的时候用的到。

//多条件组合查询
public List<Customer>  cquery(Customer criteria){
    //组合查询
    StringBuilder sb=new StringBuilder("select * from t_customer where 1=1 ");
    List<Object>params=new ArrayList<>();
    if (criteria.getCname()!=null && !criteria.getCname().trim().isEmpty()){
        sb.append("and cname like ?");
        params.add("%"+criteria.getCname()+"%");
    }
    if (criteria.getGender()!=null && !criteria.getGender().trim().isEmpty()){
        sb.append("and gender=?");
        params.add(criteria.getGender());
    }
    if (criteria.getCellphone()!=null && !criteria.getCellphone().trim().isEmpty()){
        sb.append("and cellphone like ?");
        params.add("%"+criteria.getCellphone()+"%");
    }
    if (criteria.getEmail()!=null &&  !criteria.getEmail().trim().isEmpty()) {
        sb.append("and email like ?");
        params.add("%"+criteria.getEmail()+"%");
    }
    //将参数放进object数组
    System.out.println(params);
    System.out.println(sb);
    try {
        //该方法需要一个字符串,一个结果集和一个参数集合
        return qr.query(sb.toString(),new BeanListHandler<>(Customer.class) ,params.toArray());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

多条件组合查询,提供高级搜索和模糊搜索的能力,模糊搜索使用SQL查询语句中插入"_“和”%"来实现。组合查询: 你可以提供零或多个条件,最终将提供符合提供所有条件的搜索结果。可以用StringBuilder组合SQL模板来实现。

这样DAO层就搭建完成。

猜你喜欢

转载自blog.csdn.net/weixin_43330321/article/details/82961572