简体   繁体   中英

SQLite Update Query Not Working

I'm running an update query that compiles. But when I test the results, there seem to be no changes. Everything looks good to me, but clearly something is wrong. Can anyone see what I am missing. Pretty new to SQLite, so apologies if it's something simple. Thanks!

public static Boolean updateHealth (int unitVal, int oldValue, int newValue) {
    String unit = Integer.toString(unitVal);
    String oldVal = Integer.toString(oldValue);
    String newVal = Integer.toString(newValue);

    System.err.printf("old val: %s, new val: %s\n", oldVal, newVal);
    SQLiteDatabase db = myDBOpenHelper.getWritableDatabase();
    String where = UNIT_COLUMN + " = " + unit + " AND " + HEALTH_COLUMN + " = " + oldVal;

    Cursor cursor = db.query(UNITS_TABLE, new String[] {UNIT_COLUMN}, where, null, null, null, null);

    if (cursor != null) {
        /* the record doesn't exist, cancel the operation */
        return false;
    }

    ContentValues updatedValues = new ContentValues();
    updatedValues.put(HEALTH_COLUMN, newVal);

    /* SQL query clauses */
    String whereArgs[] = null;

    db.update(UNITS_TABLE, updatedValues, where, whereArgs);

    return true;
}

The cursor is not null when no row is retrieved. So you have to replace the line if (cursor != null) { by if(!cursor.moveToNext()) {

By the way, you don't need to query the database before updating. You can do the update, see how many rows have been affected and return true if the number of affected rows is > 0, false otherwise. The number of affected rows is returned by the method update .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM