Search code examples
javasqluser-input

SQL query for user t1, t2, . . . , tm terms in where clause


User gives String as input of terms they can be t1, ...tm now I have to embed these t1,... tm in sql where clause. Select * from documents where term = t1 OR term = t2 ...... term=tm

At the moment I am splitting string into string array:

String[] terms = term.split("\\s+");     
 for (int i =0; i<term.length; i++) {
     if (i == term.length -1) {
     str += "term = " + term[i];
}
else {
    str += "term = " + term[i] + " OR ";
}

Now I am getting

string str= "term = document OR term = word Or term = explanation".

But term is my column name and document value how can I pass this in where clause of SQL?


Solution

  • I assume, since you are splitting by spaces, that the user's input is like this:

    document word explanation
    

    First use trim() to remove any leading spaces from term.
    Then inside the for loop enclose all the items of the array in single quotes (although this is not the safe way to construct a query, you could use a Prepared Statement and ? placeholders):

    String[] terms = term.trim().split("\\s+");
    for (int i = 0; i < terms.length; i++) {
        str += "term = '" + terms[i] + "'";
        if (i < terms.length -1) {
            str += " OR ";
        }
    }
    

    The result will be:

    term = 'document' OR term = 'word' OR term = 'explanation'