【发布时间】: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