Sqlite Query for multiple values ​​in one column

I wanted to make a query in the table for the field identifier with some values, for example, 1,5,4,11, which will come from the previous screen according to the choice.

cursor = database.query(tablename, new String[] { "TopName" }, "id =?", new String[]{"2,3"}, null, null, null); 

When I like it, I get the number of counters 0, with a new String [] {"2"} I get the value that I want for all identifiers with values ​​in an array of strings, such as OR, that have a value in this column.

+5
source share
6 answers

You can use the IN operator as follows:

 cursor = database.query(tablename, new String[] {"TopName"}, "id IN(?,?)", new String[]{"2","3"}, null, null, null); 
+16
source

The correct syntax for using the IN operator in Android ContentProvider is as follows:

 cursor = database.query(contentUri, projection, "columname IN(?,?)", new String[]{"value1" , "value2"}, sortOrder); 

Alternatively, we can also use

 cursor = database.query(contentUri, projection, "columnName IN(?)", new String[] {" 'value1' , 'value2' "}, sortOrder); 

Note that we need single quotes around each value, separated by commas, in the arguments for the second case, otherwise the whole row will be considered as one value for the column. SQL will consider it as

SELECT * FROM table WHERE columnName IN ('value1, value2')

instead of the correct syntax

SELECT * FROM table WHERE columnName IN ('value1', 'value2')

+15
source

VolkerK was the first to correctly answer the question, but for completeness, here is a complete example of using the IN operator:

 cursor = database.query(tablename, new String[] { "TopName" }, "id IN (?)", new String[]{"2,3"}, null, null, null); 
+4
source

Use the IN operator instead of comparing equality (=).

+3
source

In the SelectionArgs section, I think you need to change:

 new String[]{"2,3"} 

To

 new String[]{"2","3"} 
+1
source

I would like to add this here because the collection of answers helped me add some (unknown) values ​​to SQLiteDatabase.query() , and the single-question mark did not work for me. Hope helps anyone

 // API > 24 protected String attributesAsMarks(String[] attributes) { List<String> marks = Collections.nCopies(attributes.length, "?"); return marks.stream().collect(Collectors.joining(",")); } // I'm using API > 15 protected String attributesAsMarks(String[] attributes) { StringBuilder sb = new StringBuilder(); String separator = ""; for (String s : attributes) { if (s == null) continue; sb.append(separator).append("?"); separator = ","; } return sb.toString(); } 

Thanks

0
source

Source: https://habr.com/ru/post/943946/


All Articles