Sqlite Query for multiple values in one column

后端 未结 6 744
孤城傲影
孤城傲影 2020-12-30 14:07

I wanted to do query in table for field id with some vales like 1,5,4,11 which will come from previous screen according to selection.

cursor = database.query         


        
相关标签:
6条回答
  • 2020-12-30 14:27

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

    0 讨论(0)
  • 2020-12-30 14:31

    You can use the IN operator like this,

    cursor = database.query(tablename, new String[] {"TopName"}, "id IN(?,?)", 
                                            new String[]{"2","3"}, null, null, null);
    
    0 讨论(0)
  • 2020-12-30 14:32

    The correct syntax for using the IN operator in Android's 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 comma-separated value in the arguments for second case, otherwise the whole string will be treated as one value for the column. The SQL will treat it as

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

    instead of the correct syntax

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

    0 讨论(0)
  • 2020-12-30 14:41

    I would like to put this here since a compendium of answers helped me putting multiple (unknown) values in SQLiteDatabase.query() and the one-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 to

    • @Lalit
    • https://stackoverflow.com/a/5600690/1358777
    • https://stackoverflow.com/a/38546936/1358777
    • https://stackoverflow.com/a/524089/1358777
    0 讨论(0)
  • 2020-12-30 14:48

    For the SelectionArgs section I think you need to change:

    new String[]{"2,3"}
    

    To

    new String[]{"2","3"}
    
    0 讨论(0)
  • 2020-12-30 14:52

    VolkerK was first to correctly answer the question, but for the sake of completeness here is a full example of how to use the IN operator:

    cursor = database.query(tablename,
                    new String[] { "TopName" }, "id IN (?)", new String[]{"2,3"}, null, null, null);
    
    0 讨论(0)
提交回复
热议问题