0

I want to update multiple rows. Like make status=false where status=true and make status=true where id=x

try {
    String where = "id=?";
    String[] whereArgs = new String[] { Id };

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues initialValues = new ContentValues();
    initialValues.put("status", "true");
    db.update(TABLE_PROJECT, initialValues, where, whereArgs);
    db.close();
} catch (Exception e) {
    Log.e("Exception in update query", e.toString());
}

Currently what happens i am able to update the status first time but when it comes next time i need to change the previous status to false and then update new one with true. I searched and found that it can be done with switch case but here how can we apply this?

4

2 回答 2

0

为了能够读取旧status值,您必须在单个查询中进行两次更新。你是对的,这需要一个CASE 表达式;像这样的东西:

UPDATE Project
SET status = CASE
             WHEN status = 'true' THEN 'false'
             WHEN id = 'x'        THEN 'true'
             END
WHERE status = 'true' OR id = 'x'  -- don't change other records

该类ContentValues仅支持文字值,不支持表达式,因此您必须rawQuery改用:

db.rawQuery("UPDATE "+TABLE_PROJECT+" "+
            "SET status = CASE "+
            "WHEN status = 'true' THEN 'false' "+
            "WHEN id = ?1         THEN 'true' "+
            "END "+
            "WHERE status = 'true' OR id = ?1",
            new String[] { Id });

(这里假设id是一个字符串;如果不是,则不需要使用参数。 ?1是第一个参数。)

于 2013-05-20T16:46:43.503 回答
-3
try {

    String where = "id=? or status=?";
    String[] whereArgs = new String[] { Id,"false" };

    SQLiteDatabase db = this.getWritableDatabase();
    ContentValues initialValues = new ContentValues();
    initialValues.put("status", "true");
    db.update(TABLE_PROJECT, initialValues, where, whereArgs);
    db.close();
} catch (Exception e) {
    Log.e("Exception in update query", e.toString());
}
于 2013-05-20T14:00:24.800 回答