Android SQLite db.update() add values [duplicate]

2019-03-03 07:36发布

问题:

This question already has an answer here:

  • android update database column based on the current column value 2 answers

I'm using the method db.update() to change a value of a field in the table. when I insert the new value it is possible sum it with the existing?

 public void Trasf() {
String value = Scegli.getText().toString();
        cv.put(CTable.PREL, mI.getText().toString());

        SQLiteDatabase db = mHelper.getWritableDatabase();

        db.update(CTable.TABLE_NAME, cv, CTable.NO + " = ?",  new String[] { value });

        db.close();
}
    }

回答1:

Not exactly sure what you want to do but perhaps:

 public void Trasf() { 

        String value = Scegli.getText().toString();

        // add two strings or numbers together in the .put method
        cv.put(CTable.PREL, mI.getText().toString() + " " + oldString); // for string
        cv.put(CTable.PREL, int_new + int_old); // adding numbers

        SQLiteDatabase db = mHelper.getWritableDatabase();

        db.update(CTable.TABLE_NAME, cv, CTable.NO + " = ?",  new String[] { value });

        db.close(); }
    }


回答2:

The ContentValues object allows only simple values.

To do calculations, you have to write the SQL yourself and call execSQL:

public void Trasf() {
    SQLiteDatabase db = mHelper.getWritableDatabase();
    try {
        db.execSQL("UPDATE " + CTable.TABLE_NAME +
                   " SET " + CTable.PREL + " = " + CTable.PREL + " + ?" +
                   " WHERE " + CTable.NO + " = ?",
                   new Object[] { mI.getText().toString(),
                                  Scegli.getText().toString() });
    } finally {
        db.close();
    }
}


回答3:

Change

CTable.NO + " = ?"

to

CTable.NO + " = " + CTable.NO + " + ?"



回答4:

You need to first retrieve the existing value using a select command and then in cv.

Retrieve the value using a cursor and store it in a local variable.

Existing+new value

Now write your update statement.