当我们需要开发一个方法用来查询数据库的时候,往往会遇到这样一个问题:就是不知道用户到底会输入什么条件,那么怎么样处理sql语句才能让我们开发的方法不管接受到什么样的条件都可以正常工作呢?这时where 1=1加上list就可以完美解决这个问题了,废话少说,上代码: 1 ...
当我们需要开发一个方法用来查询数据库的时候,往往会遇到这样一个问题:就是不知道用户到底会输入什么条件,那么怎么样处理sql语句才能让我们开发的方法不管接受到什么样的条件都可以正常工作呢?这时where '1'='1'加上list就可以完美解决这个问题了,废话少说,上代码:
1 // 模糊查询方法 2 public List<person> query() { 3 List<person> list = new ArrayList<>(); 4 Connection con = null; 5 Scanner sc = new Scanner(System.in); 6 System.err.println("enter name:"); 7 String name = sc.nextLine(); 8 System.err.println("enter id:"); 9 String id = sc.nextLine();10 System.err.println("enter tel:");11 String tel = sc.nextLine();12 System.err.println("enter sex:");13 String sex = sc.nextLine();14 String sql = "select id,name,tel,sex from students "15 // 技巧在此,合理拼接字符串16 + "where 1=1";17 List<Object> list1 = new ArrayList<Object>();18 //使用 commons-lang包19 if (StringUtils.isNotEmpty(name)) {20 sql += " and title like ?";21 list1.add("%" + name + "%");22 }23 24 if (!StringUtils.isEmpty(id)) {25 sql += " and content like ?";26 list1.add("%" + id + "%");27 }28 29 if (!StringUtils.isEmpty(tel)) {30 sql += " and addr like ?";31 list1.add("%" + tel + "%");32 }33 try {34 con = DSUtlis.getConnection();35 // SQL语句组成完成以后,就生成pst对象36 PreparedStatement pst = con.prepareStatement(sql);37 // 设置?的值38 for (int i = 0; i < list1.size(); i++) {39 pst.setObject(i + 1, list.get(i));40 }41 ResultSet rs = pst.executeQuery();42 while (rs.next()) {43 person p = new person();44 p.setId(rs.getString("id"));45 p.setName(rs.getString("name"));46 p.setTel(rs.getString("tel"));47 p.setSex(rs.getString("sex").equals("1") ? "男" : "女");48 list.add(p);49 }50 rs.close();51 pst.close();52 } catch (Exception e) {53 e.printStackTrace();54 } finally {55 try {56 con.close();57 } catch (SQLException e) {58 e.printStackTrace();59 }60 }61 return list;62 }
原标题:JAVA 模糊查询方法
关键词:JAVA
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。