这篇文章主要为大家详细介绍了Java模糊查询方法的实现,实例教你如何用Java做模糊查询结果,感兴趣的小伙伴们可以参考一下
当我们需要开发一个方法用来查询数据库的时候,往往会遇到这样一个问题:就是不知道用户到底会输入什么条件,那么怎么样处理sql语句才能让我们开发的方法不管接受到什么样的条件都可以正常工作呢?这时where '1'='1'加上list就可以完美解决这个问题了,废话少说,上代码:
// 模糊查询方法
public List query() {
List list = new ArrayList<>();
Connection con = null;
Scanner sc = new Scanner(System.in);
System.err.println("enter name:");
String name = sc.nextLine();
System.err.println("enter id:");
String id = sc.nextLine();
System.err.println("enter tel:");
String tel = sc.nextLine();
System.err.println("enter sex:");
String sex = sc.nextLine();
String sql = "select id,name,tel,sex from students "
// 技巧在此,合理拼接字符串
+ "where 1=1";
List list1 = new ArrayList();
//使用 commons-lang包
if (StringUtils.isNotEmpty(name)) {
sql += " and title like ?";
list1.add("%" + name + "%");
}
if (!StringUtils.isEmpty(id)) {
sql += " and content like ?";
list1.add("%" + id + "%");
}
if (!StringUtils.isEmpty(tel)) {
sql += " and addr like ?";
list1.add("%" + tel + "%");
}