emilsjolander / sprinkles

Sprinkles is a boiler-plate-reduction-library for dealing with databases in android applications
Apache License 2.0
772 stars 84 forks source link

Sql IN Statemenr #70

Open brescia123 opened 10 years ago

brescia123 commented 10 years ago

How can I make a query with the IN statement?

jdreesen commented 10 years ago

Afaik there is no helper which auto-expands the params for you. But you could simply do this:

Query.many(YourModel.class, "SELECT * FROM YourModel WHERE column IN (?, ?)", "value1", "value2");
brescia123 commented 10 years ago

Ok, but if I don't know the number of parameters I can't use this. I have to manually construct the sql query, right?

jdreesen commented 10 years ago

Yeah, something like this should do:

String[] params = new String[] {"value1", "value2", "value3", ...};

StringBuilder placeholder = new StringBuilder();
for (int i = 1; i <= params.length; i++) {
    placeholder.append("?");
    if (i < params.length) {
        placeholder.append(",");
    }
}

Query.many(YourModel.class, "SELECT * FROM YourModel WHERE column IN (" + placeholder.toString() + ")", params);

But maybe @emilsjolander comes with a better solution.

emilsjolander commented 10 years ago

@jdreesen is correct, this is the best solution currently. We should maybe look into adding a helper method for this. Of the top of my head i am thinking something a long the lines of

ArrayParam param = new ArrayParam(array)

param.commas() -> "?,?,?"
param.args() -> [obj1, obj2, obj3]