javaweb mysql模糊查询_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 + "%");

}

try {

con = DSUtlis.getConnection();

<
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值