Search code examples
androidsqliteandroid-sqlitesqliteopenhelper

Run OR statement in SQLiteOpenHelper for the same column


I have a function in my DatabaseHelper class (extends SQLiteOpenHelper) that returns row based on a certain column's value. Code snippet as follows:

Cursor cursor = db.query(TABLE_LOCATIONS, new String[]{}, COLUMN_PROD_ID+"=?", productId, null, null, null);

Where productId is a String[] that contains only 1 value.

Now I want to reuse the same function for matching 2 values for the same column. Something like:

SELECT * FROM TABLE WHERE COLUMN1 = VALUE1 OR COLUMN1 = VALUE2;

How can I achieve this in SQLiteOpenHelper. Kindly bear with me if this is a stupid question. Thanks.


Solution

  • This has nothing to do with SQLiteOpenHelper.

    The WHERE clause is the selection parameter; just change it approrpiately:

    String selection;
    switch (productIdsArray.length) {
    case 1: selection = COLUMN_PROD_ID + " = ?";
            break;
    case 2: selection = COLUMN_PROD_ID + " = ? OR " + COLUMN_PROD_ID + " = ?";
            break;
    default: // blow up
    }
    db.query(TABLE_LOCATIONS, new String[]{},
             selection, productIdsArray,
             null, null, null);