Java操作SQL逐步截断输入模糊匹配及查询结果去空格实现问询
Java实现前缀逐步匹配SQL查询及结果去空格方案
完整修改后代码
public Output method(String input) throws Exception { Output output = null; // 使用try-with-resources自动关闭连接、语句、结果集,避免资源泄漏 try (Connection connection = getSQLConnection(); PreparedStatement ps = connection.prepareStatement("SELECT COL1, COL2, COL3 FROM TABLE WHERE INPUT LIKE ?")) { if (connection == null) { logger.error("数据库连接获取失败"); return null; } String currentInput = input; // 循环逐步截断末尾字符,直到查询到结果或输入为空 while (currentInput.length() > 0) { ps.setString(1, currentInput + "%"); logger.debug("Executed: SELECT COL1, COL2, COL3 FROM TABLE WHERE INPUT LIKE ?; input => [{}]", currentInput + "%"); try (ResultSet rs = ps.executeQuery()) { if (rs.next()) { output = new Output(); // 去除所有空格:使用replaceAll匹配所有空白字符替换为空 output.setOut1(rs.getString(1) == null ? null : rs.getString(1).replaceAll("\\s+", "")); output.setOut2(rs.getString(2) == null ? null : rs.getString(2).replaceAll("\\s+", "")); output.setOut3(rs.getString(3) == null ? null : rs.getString(3).replaceAll("\\s+", "")); // 匹配到结果直接跳出循环 break; } else { logger.debug("当前前缀{}无匹配结果,截断末尾字符继续查询", currentInput); // 截断最后一位 currentInput = currentInput.substring(0, currentInput.length() - 1); } } } if (output == null) { logger.debug("所有前缀均无匹配结果"); } } return output; }
需求实现说明
- 逐步截断末尾字符迭代查询实现:
新增while循环控制查询逻辑,每次查询无结果时调用substring(0, currentInput.length() - 1)去掉当前输入的最后一位,直到查询到结果或输入字符串长度为0(无任何匹配)时终止循环 - 查询结果全空格去除实现:
调用String类的replaceAll("\\s+", "")方法,\\s+正则匹配所有空白字符(包括空格、制表符等),直接替换为空字符串,即可一次性去掉前后和中间的所有空格,符合' AB C '转'ABC'的需求
注意点
- 原代码存在笔误:
output.setOut2(rs.getString(3))应改为output.setOut3(rs.getString(3)),已在示例代码中修正 - 示例使用try-with-resources语法自动关闭JDBC相关资源,避免手动关闭遗漏导致的资源泄漏问题
- 增加了空值判断,避免查询结果为null时调用字符串方法抛出空指针异常
内容的提问来源于stack exchange,提问作者dcd
相关产品推荐
相关产品推荐

