Android rawQuery - Is there a way to use parametrized "IN" for a collection of data

Go To StackoverFlow.com

4

I am trying to use dynamically created list in WHERE, for example:

select * from books where id in (123, 120, 125) and bookCover = 'Hardcover'

I want to use it with rawQuery and I have prepared SQL in "?" form, for example:

select * from books here id in (?) and bookCover = ?

is there any way, how to put a list of "ids" in the IN clause of the select? or do I have to forget about prepared statements with "?" ?

Thanks in advance for any help. Searched

2012-04-04 19:50
by premma


3

No - I do NOT know ANY DB (like Oracle, SQL Server, SQLite, Postgres etc.) which provides for what you ask...

The nearest solution you can get is to insert the IDs into a second table and then use a subquery in the IN part...

MyIDTable hat 2 fields QNO (is just a key) and ID (contains the IDs you want in your IN... you first insert 3 rows with the same QNO and the respective IDs...

INSERT INTO MyIDTable (QNO, ID) VALUES (3, 120);
INSERT INTO MyIDTable (QNO, ID) VALUES (3, 123);
INSERT INTO MyIDTable (QNO, ID) VALUES (3, 125);

Then you can do a SELECT like this:

select * from books where id in (SELECT T.ID FROM MyIDTable T WHERE T.QNO = 3) and
bookCover = 'Hardcover'

Which basically allows for this:

select * from books where id in (SELECT T.ID FROM MyIDTable T WHERE T.QNO = ?) and
bookCover = ?

After you are done looking for that specific set of IDs you can clean up by DELETE FROM MyIDTable WHERE QNO = 3.

2012-04-04 19:57
by Yahia
Hmm, i was affraid that that will be the answer. I know, it can be done in native query in hibernate, but... Well, this is not that case :- - premma 2012-04-04 20:12
@premma hibernate does behind the scenes basically what I describe above (since no DB engine I know of supports this natively) - Yahia 2012-04-04 20:17
@premma please don't forget to upvote/mark as accepted ansewrs that are of help (see http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) - Yahia 2012-04-04 20:18
Thank you.. I was expecting this answer, but I wanted to be sure. The hint you gave me is helpful, i will think about that. Thank you once again for your quick answer - premma 2012-04-04 20:20
@premma you are welcome :- - Yahia 2012-04-04 20:21
Ads