我正在研究搜索功能,我正在将搜索查询拆分为单独的单词。我知道不会超过10个单词,但可能会少一些。
由于我需要进行SQL查询,使用一致的单词数量,让我们说10,我需要添加8个空白单词,以防用户只输入2个。
有没有聪明的方法怎么做或者我应该从1到10进行循环并检查该特定位置是否为空,如果是,则用空白字填充它?
SQL查询看起来像这样(但有9个AND):
SELECT * FROM mytable
WHERE column1 LIKE '%word1%'
AND column1 LIKE '%word2%'
AND column1 LIKE '%word3%'
基本上我想做的就是这个,但也许是以更聪明的方式:
String[] finalSearch = new String[10];
String[] search=searchInput.split(" ", -1);
for (int i=0; i<10; i++){
if (search[i]!=null){
finalSearch[i] = search[i];
}else{
finalSearch[i]="";
}
}
答案 0 :(得分:1)
假设您有一个包含您要搜索的条款的列表:
// List<String> terms
StringBuilder sqlQuery = new StringBuilder("SELECT * FROM mytable ");
if (terms.isEmpty()) { throw new IllegalArgumentException("SOME DESCRIPTION HERE") }
sqlQuery.append("WHERE column1 LIKE ? ");
for (int i = 1; i < terms.length(), i++) {
sqlQuery.append("AND column1 LIKE ? ");
}
PreparedStatement preparedStatement = null;
Connection connection = null;
try {
// Get your JDBC connection as usual
// connection = getJdbcConnection();
preparedStatement = connection.prepareStatement(sqlQuery.toString());
for (int i = 0; i < terms.length(), i++) {
preparedStatement.setString(i + 1, "%" + terms[i] + "%");
}
} catch (SQLException e) {
// Do something here with he exception
} finally {
// Make sure you close JDBC resources here
}
答案 1 :(得分:1)
您可以生成查询,具体取决于用户输入:
static String getQuery(String ... userInput){
StringBuilder sb=new StringBuilder("SELECT * FROM mytable");
if (userInput.length>0){
sb.append(" where");
for (int i=0;i<userInput.length;i++){
sb.append(" column1 LIKE '%"+userInput[i]+"%'");
if (i!=userInput.length-1) sb.append(" AND");
}
}
sb.append(";");
return sb.toString();
}
答案 2 :(得分:0)
您可以使用仅需要的单词来构建查询,而不是使用固定数量的单词(10)吗?
你可以这样做:
String [] words = search.split ();
query = "SELECT * FROM my table WHERE";
for (int i = 0; i < words.length; i++){
query += "columns LIKE " + words[i];
If (i < words.length - 1)
query += "AND";
}