Reputation: 7240
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?
Upvotes: 2
Views: 1932
Reputation: 2783
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));
Upvotes: 2
Reputation: 157437
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"});
Upvotes: 5