PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, October 24, 2022

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

 October 24, 2022     android, android-sqlite, java, sql-update, sqlite     No comments   

Issue

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();
}


Answered By - forpas
Answer Checked By - David Goodson (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing