以下是通过串字符串的方式实现查询:
@Test public void query1() throws Exception{ QueryRunner run = new QueryRunner(DataSourceUtils.getDatasSource()); Contact c = new Contact(); //c.setId("C001"); c.setName("王"); //c.setSex("1"); //c.setTel("123"); //c.setAddr("中国"); //c.setAge(88); String sql = "select * from contacts where 1=1"; if(c.getId()!=null){ sql+=" and id=‘"+c.getId()+"‘"; } if(c.getSex()!=null){ sql = sql+" and sex=‘"+c.getSex()+"‘"; } if(c.getName()!=null){ sql+=" and name like ‘%"+c.getName()+"%‘"; } if(c.getAddr()!=null){ sql+=" and addr like ‘%"+c.getAddr()+"%‘"; } if(c.getTel()!=null){ sql+=" and tel like ‘%"+c.getTel()+"%‘"; } System.err.println(">>>>>>:"+sql); List<Contact> cs = run.query(sql,new BeanListHandler<Contact>(Contact.class)); for(Contact cc:cs){ System.err.println(cc); } }
//不确定条件的查询 @Test public void query1() throws Exception{ QueryRunner run = new QueryRunner(DataSourceUtils.getDatasSource()); Contact c = new Contact(); //c.setId("C001"); c.setName("王‘"); c.setSex("1"); c.setTel("123"); c.setAddr("中国"); c.setAge(55); String sql = "select * from contacts where 1=1 ";//匹配后面的所有and List<Object> params = new ArrayList<Object>(); if(c.getId()!=null){ sql+=" and id=?"; params.add(c.getId()); } if(c.getSex()!=null){ sql = sql+" and sex=?"; params.add(c.getSex()); } if(c.getName()!=null){ sql+=" and name like ?"; params.add("%"+c.getName()+"%"); } if(c.getAddr()!=null){ sql+=" and addr like ?"; params.add("%"+c.getAddr()+"%"); } if(c.getTel()!=null){ sql+=" and tel like ?"; params.add("%"+c.getTel()+"%"); } if(c.getAge()!=null){ sql+=" and age=?"; params.add(c.getAge()); } System.err.println(">>>>>>:"+sql); System.err.println(params); List<Contact> cs = run.query(sql, new BeanListHandler<Contact>(Contact.class), params.toArray()); for(Contact cc:cs){ System.err.println(cc); } }
时间: 2024-10-18 02:59:43