Search code examples
androidsqlitedynamicwhere-clause

SQLite dynamic query


I have a SQLite database, and what i want to do is that an user selects a filter. For example i have a database of books, and a user just want to look data from "Agata christies books"..

So i made a spinner with the options to select, and then with an intent i pass the field selected to another activity which executes the query select.

My question is, how can i make the dynamic query? Think that i have more than 1 filter, how can i make the clause WHERE depending on the data i passed from the other activity by an intent?

thanks


Solution

  • Lazy way but tried and true:

    String query = "Select id FROM books WHERE 1=1"
    if (condition1) query+= " AND name="+theName;
    if (condition2) query+= " AND author="+theAuthor;
    if (condition3) query+= " AND price="+thePrice;
    

    If you have full control of options aka via spinners, this is safe. If its an edittext, use preparedStatements and bind the arguments to avoid SQLI.