0

我需要使用 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");
      }
   }
}

4

1 回答 1

0

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

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

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

output.setOut1(rs.getString(1).replaceAll("\\s", ""));
于 2021-10-28T01:08:46.097 回答