2

I have the following code which I was using to update a single row in my database:

public int updateSentFieldForIncomingMessage(IncomingMessage incomingMessage)
{
    SQLiteDatabase db;
    int numberOfRowsAffected;

    try
    {
        db = super.getWritableDatabase();
    }
    catch (SQLiteException e)
    {
        File dbFile = context.getDatabasePath(DATABASE_NAME);
        db = SQLiteDatabase.openDatabase(dbFile.getAbsolutePath(), null, SQLiteDatabase.NO_LOCALIZED_COLLATORS);
    }

    try
    {
        ContentValues values = new ContentValues();
        values.put(KEY_MESSAGE_SENT, true);

        numberOfRowsAffected = db.update(TABLE_INCOMING_MESSAGES, values, KEY_ID + " = ?", new String[]{String.valueOf(incomingMessage.getId())});
    }
    finally
    {
        db.close();
    }

    return numberOfRowsAffected;
}

This works fine but now I'd like to refactor the method so that instead of a single IncomingMessage parameter, it accepts a list of IncomingMessage. But when I get to this statement:

db.update(TABLE_INCOMING_MESSAGES, values, KEY_ID + " = ?", new String[]{String.valueOf(incomingMessage.getId())});

I'm not sure how to modify it so that I can specify multiple rows (via KEY_ID) in my WHERE clause. What I'd like to do is say something like KEY_ID IN ( <multiple row IDs here> ). Is that possible?

2 Answers 2

5

Is that possible?

it is, but you will need a number of ? equals to the length of String[]. You can use a String builder to create such whereClause.

E.g.

db.update(TABLE_INCOMING_MESSAGES, values, KEY_ID + " IN ( ?, ?, ?, ?)", new String[]{String.valueOf(incomingMessage.getId()),  "id1", "id2", "id3"});
Sign up to request clarification or add additional context in comments.

3 Comments

So if my list had 5 values in it, you mean something like KEY_ID + " = ? OR ? OR ? OR ? OR ?", is that correct?
KEY_ID IN ( ?, ?, ?, ?), new String[] {"id0", "id1", "id2", "id3"}
Ahh, ok. I've got it now. Thanks very much!
2

In case you have unknown number of arguments, you can also use:

String args = TextUtils.join(", ", arrayOfIds);

db.execSQL(String.format("UPDATE %s SET %s = true WHERE %s IN (%s);", 
    TABLE_INCOMING_MESSAGES, KEY_MESSAGE_SENT, KEY_ID, args));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.