[英]Deduct one character until a row is returned, and trim spaces when returning values [Java/SQL]
我需要使用 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");
}
}
}
對於扣除字符,應該這樣做:
for(int i = 0; i < input.length(); i++){
ps.setString(1, input.substring(0, input.length()-i));
}
對於修剪空間,它應該是:
output.setOut1(rs.getString(1).replaceAll("\\s", ""));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.