I need to make a sample from the database but I do not know the number of parameters for which I am looking. Request example

SELECT Ingredients.name FROM Ingredients WHERE Ingredients._id IN (?); 

Where the question mark - there may be several parameters. Example

 SELECT Ingredients.name FROM Ingredients WHERE Ingredients._id IN ('1' , '4'); 

I do queries in DB Browser for SQLite - everything works. I'm doing in Java, under Android, here's a query

 cursor c2 = myDbHelper.rawQuery("SELECT Ingredients.name " + "FROM Ingredients" + "WHERE Ingredients._id IN(?);", new String[]{"'1' , '2'"}); 

does not work.

Tried on everyone

 new String[]{"'1 , 2'"} и new String[]{"1 , 2"} 

and as soon as it is not perverted - it does not work. Help

https://stackoverflow.com/questions/8343946/sqlite-query-for-multiple-values-in-one-columm

It did not help

    1 answer 1

    Do this:

     String[] inParams = { "1", "2" }; String query = "SELECT Ingredients.name FROM Ingredients" + " WHERE Ingredients._id IN (" + makeParams(inParams.length) + ")"; Cursor cursor = myDbHelper.rawQuery(query, inParams); 

    Implement the makeParams method:

     private String makeParams(int length) { if (length < 1) { throw new RuntimeException("Нет условий для поиска"); } else { StringBuilder sb = new StringBuilder(length * 2 - 1); sb.append("?"); for (int i = 1; i < length; i++) { sb.append(",?"); } return sb.toString(); } } 
    • Thanks helped. But is there no more elegant way? This does not look correct. - Anton