处理多项查询的sql怎么处理?(不知道怎么表达,参见详情如下)
就是我在做信息查找的时候会有好多表单,如下:
这样可以让他有选择,可能还有好多项,但是无论他添什么信息进行查找都能实现查找;
但是问题就来了:
我怎么在sql里面进行处理呢,如果按照一般的思维来想得话:我用select * from note where 什么什么?我在这里
必须要定死得,或者说必须能接受到参数,如果接受到的参数为空的话,那么sql一定会报错的,在这里我要怎么处理呢?
麻烦高手给一个具体的结果方式,或者给一个精确的算法,谢谢了。
[解决办法]
最简单的办法,拼串
String sql="select * from note where 1=1";if(name != null){ sql+=" and name='"+name+"'";}if(school != null){ sql+=" and school='"+school+"'";}
[解决办法]
public List<Employee> specificInquiresr(String ename, String gender, String age, String salary, String deptno) throws SQLException { Connection conn = DBUtil.getConnection(); List<Employee> employees = new ArrayList<Employee>(); StringBuffer sql = new StringBuffer(); sql.append("select * from employee_w where 1=1"); //String ename1 = ename.trim(); if(ename.trim()!=""){ sql.append(" and ename like '%" + ename +"%'"); } if(gender.equals("0")){ sql.append(""); }else if(gender.equals("1")){ sql.append(" and gender='男'"); }else if(gender.equals("2")){ sql.append(" and gender='女'"); } if(age!=""){ sql.append(" and age= " + age); } if(salary.equals("0")){ sql.append(" " ); }else if(salary.equals("1")){ sql.append(" and salary<3000" ); }else if(salary.equals("2")){ sql.append(" and salary between 3000 and 5000" ); }else if(salary.equals("3")){ sql.append(" and salary between 5000 and 7000" ); }else if(salary.equals("4")){ sql.append(" and salary between 7000 and 9000" ); }else if(salary.equals("5")){ sql.append(" and salary>9000" ); } if(deptno.equals("0")){ sql.append(" "); }else if(deptno.equals("1")){ sql.append(" and deptno='1001'"); }else if(deptno.equals("2")){ sql.append(" and deptno='1002'"); }else if(deptno.equals("3")){ sql.append(" and deptno='1003'"); }else if(deptno.equals("4")){ sql.append(" and deptno='1004'"); } String sql1 = sql.toString(); PreparedStatement ps = conn.prepareStatement(sql1); System.out.println(sql1); ResultSet rs = ps.executeQuery(); while(rs.next()){ Employee e = new Employee(); e.setId(rs.getLong("id")); e.setEname(rs.getString("ename")); e.setGender(rs.getString("gender")); e.setAge(rs.getInt("age")); e.setSalary(rs.getDouble("salary")); e.setDeptno(rs.getLong("deptno")); employees.add(e); } return employees; }
------解决方案--------------------
Map<String,String> map = new HashMap<String,String>map.put("name",request.getParamter("name"));map.put("address",request.getParamter("address"));