//按照参数集合进行查询
public List<Goddess> queryByParams(List<Map<String,Object>> params) throws Exception{
List<Goddess> goddesses = new ArrayList<Goddess>();
Connection conn = DBHelper.getConn();
StringBuilder sb = new StringBuilder();
sb.append("select * from imooc_goddess where 1=1 ");
if (params!=null&¶ms.size()>0){
for (int i=0;i<params.size();i++) {
if(i == 0){
Map<String, Object> param = params.get(i);
sb.append(" and "+" ( " + param.get("name") + " " + param.get("relat") + " " + param.get("value") + " ");
}else if(i==1){
Map<String, Object> param = params.get(i);
sb.append(" or " + param.get("name") + " " + param.get("relat") + " " + param.get("value") + " ");
}
}
sb.append(" ) ");
}
PreparedStatement statement = conn.prepareStatement(sb.toString());
System.out.println(sb.toString());
ResultSet rs = statement.executeQuery();
Goddess g = null;
while(rs.next()){
g=new Goddess();
g.setUser_name(rs.getString("user_name"));
g.setId(rs.getInt("id"));
g.setAge(rs.getInt("age"));
g.setSex(rs.getInt("sex"));
g.setBirthday(rs.getDate("birthday"));
g.setEmail(rs.getString("email"));
g.setMobile(rs.getString("mobile"));
g.setCreate_date(rs.getDate("create_date"));
g.setCreate_user(rs.getString("create_user"));
g.setUpdate_date(rs.getDate("update_date"));
g.setUpdate_user(rs.getString("update_user"));
g.setIsdel(rs.getInt("isdel"));
goddesses.add(g);
}
return goddesses;
}
main方法:
GoddessDao gd =new GoddessDao();
List<Map<String,Object>> params = new ArrayList<Map<String,Object>>();
Map<String,Object> param1 = new HashMap<String, Object>();
param1.put("name","user_name");
param1.put("relat","=");
param1.put("value","'小美'");
params.add(param1);
Map<String,Object> param2 = new HashMap<String, Object>();
param2.put("name","mobile");
param2.put("relat","=");
param2.put("value","'187'");
params.add(param2);
List<Goddess> goddesses = gd.queryByParam(params);
for (Goddess g : goddesses){
System.out.println(g.toString());
}
是 i==0 判断不了吗?