0

i need to search string in SQL using Java, expectation is something like this:

input: 123456

data in SQL to be fetched: 123777

result is: ' AB C '

result should be: 'ABC'

iteration will be like:

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 

this is my current code:

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");
      }
   }
}

dcdum2018
  • 93
  • 1
  • 9
  • 1
    You can use `rs.getString(1).replaceAll("\\s", "")` to remove spaces. I don't really understand the problem of the other question. You just iterate over `input`, remove 1 character with each iteration till you get a result? – magicmn Oct 21 '21 at 09:34
  • yes, correct. input is `123456` but available data is `123777`, it should loop by removing the last character all the time until it reaches a match in the table – dcdum2018 Oct 21 '21 at 09:45
  • 1
    You need to create a loop (probably using while) to make this happen. – Just another Java programmer Oct 21 '21 at 09:52
  • for loop is preferable but i dont know how to do it – dcdum2018 Oct 21 '21 at 10:20

1 Answers1

0

for deduct character, this should be done:

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

for trim spaces, it should be:

output.setOut1(rs.getString(1).replaceAll("\\s", ""));
dcdum2018
  • 93
  • 1
  • 9