javasql拼串

/**
     * 模糊查询,分析出姓名,性别,年龄
     */
    public ArrayList<_students> doSearch(String name,String sex,String age) throws SQLException{
        
        int idNum = 1;
        
        conn = ConnMysql.getConn();
        
        String searchSql = "select * from students where name = ? && sex = ? && age = ? order by id limit 0,10";
        /*根据传过来数据是否为空,重组sql*/
        if(name.equals("")){
            searchSql = searchSql.replace("name = ?", "");
        }
        if(sex.equals("")){
            searchSql = searchSql.replace("&& sex = ?", "");
        }
        if(age.equals("")){
            searchSql = searchSql.replace("&& age = ?", "");
        }
        
        searchSql = searchSql.replaceAll("[^//?] &&", "");
        
        if(!searchSql.contains("=")){
            searchSql = searchSql.replace("where", "");
        }
        /*重组好的sql放进去*/
        ps = conn.prepareStatement(searchSql);
        //根据剩下几个?号,重新给定值
        if(!name.equals("")){
            ps.setString(idNum, name);
            idNum ++;
        }
        if(!sex.equals("")){
            ps.setString(idNum, sex);
            idNum ++;
        }
        if(!age.equals("")){
            ps.setString(idNum, age);
            idNum ++;
        }
        
        rs = ps.executeQuery();
        alStudents = new ArrayList<_students>();
        
        while(rs.next()){
            _students st = new _students();
            ss.setPageCount(pageCount);
            st.setType("首次");
            st.setPageNow(0);
            st.setId(rs.getString(1));
            st.setName(rs.getString(2));
            st.setSex(rs.getString(3));
            st.setAge(rs.getString(4));
            st.setHobby(rs.getString(5));
            alStudents.add(st);
        }
        
        return alStudents;
    }

小傅哥 CSDN认证博客专家 ASM 设计模式 面经手册
©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页
实付 39.90元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值