Search code examples
javaandroidsqlitesql-updateandroid-sqlite

How to add a value of a variable in a sqlite database existing column?


I would like to ask for some help with my android code. I am trying to develop a quiz app using SQLite.My Database has two Tables. One for Students Information and one for the Questions and answers. Students Information such as Name, Student ID e.c. are inputs through textViews . After taking the Quiz in the Result activity the Score shown up. But i also want this score to be kept in a column COLUMN_SCORE of Student_trable.

I tried to update the table using this method:

 `public static void addScore (int StudentScore){

    ContentValues cv = new ContentValues();
    cv.put(DataContract.StudentTable.COLUMN_SCORE, StudentScore);

    Cursor c = db.rawQuery("SELECT * FROM student_info ORDER BY id DESC LIMIT 1 " ,null);

    db.update(DataContract.StudentTable.TABLE_NAME1, cv, DataContract.StudentTable.COLUMN_SCORE +  "= ?", new String[] {String.valueOf (c)});
    db.close();`

but i failed. Any suggestion please? Here is some more details of my code:


Solution

  • You can use a subquery in the WHERE clause argument of the update() method, so that there is no need for a SELECT query to retrieve the last id:

    public static void addScore(int studentScore) {
        String table = DataContract.StudentTable.TABLE_NAME1;
        String id = DataContract.StudentTable.COLUMN_ID;
    
        ContentValues cv = new ContentValues();
        cv.put(DataContract.StudentTable.COLUMN_SCORE, studentScore);
        db.update(
            table, 
            cv, 
            id + " = (SELECT MAX(" + id + ") FROM " + table + ")", 
            null
        );
        db.close();
    }