【问题标题】:Deduct one character until a row is returned, and trim spaces when returning values [Java/SQL]减一个字符直到返回一行,返回值时修剪空格[Java/SQL]
【发布时间】:2021-12-08 01:20:15
【问题描述】:

我需要使用Java在SQL中搜索字符串,期望是这样的:

输入:123456

要获取的 SQL 中的数据:123777

结果是:' AB C '

结果应该是:'ABC'

迭代会是这样的:

select col1, col2, col3 from table where input like '123456%'; --no row returned
select col1, col2, col3 from table where input like '12345%'; --no row returned
select col1, col2, col3 from table where input like '1234%'; --no row returned
select col1, col2, col3 from table where input like '123%'; --returns row for 123777 

这是我当前的代码:

public Output Method (String input) throws exception{

   Connection connection = getSQLConnection();
   String SQLquery = "SELECT COL1, COL2, COL3 FROM TABLE WHERE INPUT LIKE ?";

   if (connection != null){
      
      PreparedStatement ps = connection.prepareStatement(SQLquery);
      ps.setString(1, input + "%"); 
      ResultSet rs = ps.executeQuery();
      
      // how to deduct characters until a match is found?
      logger.debug("Executed: "+SQLquery+"; input => ["+input+"]"); 

      if(rs.next()){
         output = new Output();
         output.setOut1(rs.getString(1));
         output.setOut2(rs.getString(2));
         output.setOut2(rs.getString(3));
         //how to remove all spaces from in per result?
         //sample result: ' AB  C   ' -> should be 'ABC'

      }else{
         logger.debug("no row returned");
      }
   }
}

【问题讨论】:

  • 您可以使用rs.getString(1).replaceAll("\\s", "") 删除空格。我真的不明白另一个问题的问题。你只是迭代input,每次迭代删除1个字符直到你得到结果?
  • 是的,正确的。输入是123456,但可用数据是123777,它应该循环删除最后一个字符,直到它在表中匹配
  • 您需要创建一个循环(可能使用 while)来实现这一点。
  • for 循环比较好,但我不知道怎么做

标签: java sql for-loop prepared-statement character-trimming


【解决方案1】:

对于扣除字符,应该这样做:

for(int i = 0; i < input.length(); i++){
   ps.setString(1, input.substring(0, input.length()-i)); 
}

对于修剪空间,它应该是:

output.setOut1(rs.getString(1).replaceAll("\\s", ""));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-29
    • 2011-02-04
    相关资源
    最近更新 更多