javasql拼串
作者:互联网
/** * 模糊查询,分析出姓名,性别,年龄 */ public ArrayListdoSearch(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(); 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; }
标签:searchSql,拼串,rs,idNum,equals,st,javasql,sex 来源: https://blog.51cto.com/u_14943622/2838716