简体   繁体   中英

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:

The Table: 在此处输入图像描述

The Debug screen:

在此处输入图像描述

Classes

 `import android.provider.BaseColumns;

   /**  This Class is creating  constant variables for the two tables of our database.    */
public final class DataContract {
private  DataContract(){}
public static class StudentTable implements BaseColumns {

    public static final String TABLE_NAME1 = "student_info";
    public static final String COLUMN_ID = "id";
    public static final String COLUMN_AM = "studentAm";
    public static final String COLUMN_NAME = "name";
    public static final String COLUMN_SEMESTER = "semester";
    public static final String COLUMN_SCORE = "score";
    public static final String COLUMN_DATE = "studentDate";
}`

/** This class links the Quiz database with SQLite where is the update method.*/

 ` public class DataDbHelper extends SQLiteOpenHelper {

/** The String stores the name of the database.*/
private static final String DATABASE_NAME = "Quiz.db";
/** The integer stores the version of the database*/
private static final int DATABASE_VERSION = 1;
private static SQLiteDatabase db;
private static volatile DataDbHelper instance = null;

/** This method creates the database.*/
public DataDbHelper (Context context) {
    super (context, DATABASE_NAME, null, DATABASE_VERSION);
}

/** This method assign details to the columns.
 *  It calls commands and statements from SQLite using Strings.*/

@Override
public void onCreate (SQLiteDatabase db) {
    /** Creates the table of questions.*/
    this.db = db;
    final String SQL_CREATE_QUESTIONS_TABLE = "CREATE TABLE " +
            QuestionTable.TABLE_NAME + " ( " +
            QuestionTable._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            QuestionTable.COLUMN_QUESTION + " TEXT," +
            QuestionTable.COLUMN_IMAGE + " TEXT," +
            QuestionTable.COLUMN_ANSWER1 + " TEXT," +
            QuestionTable.COLUMN_ANSWER2 + " TEXT," +
            QuestionTable.COLUMN_ANSWER3 + " TEXT," +
            QuestionTable.COLUMN_ANSWER4 + " TEXT," +
            QuestionTable.COLUMN_ANSWERNUM + " INTEGER " +
            ")";

    db.execSQL(SQL_CREATE_QUESTIONS_TABLE);
    fillQuestionsTable();
    /** Creates the table of students.*/
    final String SQL_CREATE_STUDENT_TABLE = "CREATE TABLE " +
            StudentTable.TABLE_NAME1 + " ( " +
            StudentTable.COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
            StudentTable.COLUMN_AM + " TEXT," +
            StudentTable.COLUMN_NAME + " TEXT," +
            StudentTable.COLUMN_SEMESTER + " TEXT," +
            StudentTable.COLUMN_SCORE + " TEXT, " +
            StudentTable.COLUMN_DATE + " TEXT " +
           ")";
    db.execSQL(SQL_CREATE_STUDENT_TABLE);

}

/** This method can be used to upgrade the tables with newer information.*/
@Override
public void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL("DROP TABLE IF EXISTS " + QuestionTable.TABLE_NAME);
    db.execSQL("DROP TABLE IF EXISTS " + StudentTable.TABLE_NAME1);
    onCreate(db);

}

/** This method fill the Question table. */
private void fillQuestionsTable() {
    Question q1 = new Question ("A is correct","arkas1", "Maria" ,"anna", "Nikos" , "Andy", 1);
    addQuestion (q1);
    Question q2 = new Question ("B is correct","arkas2", "kjbhkjhA" ,"Bkjgkgj", "Cjvjhgj" , null, 2);
    addQuestion (q2);
    Question q3 = new Question ("C is correct","arkas3", "cgxcvnx" ,"xcvnxvxv", "Cgnhxfgjxf" , null, 3);
    addQuestion (q3);
    Question q4 = new Question ("A is correct again",null, "fvjxfvA" ,"Bxfgxmg", "Cxgmxmx" , null, 1);
    addQuestion (q4);
    Question q5 = new Question ("D is correct",null, "Afghf" ,"fghxggggghB", "xfgxghxghC" , "fghxghxgh", 4);
    addQuestion (q5);

}

/** This method is used to add new question from our sqlite database.*/
private void addQuestion(Question question){
    ContentValues cv = new ContentValues();
    cv.put(QuestionTable.COLUMN_QUESTION, question.getQuestion());
    cv.put(QuestionTable.COLUMN_IMAGE, question.getImage());
    cv.put(QuestionTable.COLUMN_ANSWER1, question.getAnswer1());
    cv.put(QuestionTable.COLUMN_ANSWER2, question.getAnswer2());
    cv.put(QuestionTable.COLUMN_ANSWER3, question.getAnswer3());

    cv.put(QuestionTable.COLUMN_ANSWER4, question.getAnswer4());
    cv.put(QuestionTable.COLUMN_ANSWERNUM, question.getAnswerNum());
    db.insert(QuestionTable.TABLE_NAME, null, cv);
}

/** This method is used to add new student to our sqlite database.*/
public void addNewStudent(String studentAm, String studentName, String studentSemester, int studentScore, String studentDate){

    /** on below line we are creating a variable for
    // our sqlite database and calling writable method
    // as we are writing data in our database.*/
    SQLiteDatabase db = this.getWritableDatabase();

    // on below line we are creating a
    // variable for content values.
    ContentValues values = new ContentValues();


    // on below line we are passing all values
    // along with its key and value pair.
    values.put(StudentTable.COLUMN_AM, studentAm);
    values.put(StudentTable.COLUMN_NAME, studentName);
    values.put(StudentTable.COLUMN_SEMESTER, studentSemester);
    values.put(StudentTable.COLUMN_SCORE, studentScore);
    values.put(StudentTable.COLUMN_DATE, studentDate);

    // after adding all values we are passing
    // content values to our table.
    db.insert(StudentTable.TABLE_NAME1, null, values);

    // at last we are closing our
    // database after adding database.
    db.close();
}


/**  we have created a new method for reading all the students from Student Table.    */
public List<Student> getAllStudent() {
    List<Student> StudentList = new ArrayList<>();
    db = getReadableDatabase ();
    // Choose Random Questions
    Cursor c = db.rawQuery("SELECT * FROM student_info  ",null );


    if (c.moveToFirst()){
        do {
            Student student = new Student ();
            student.setStudentAm(c.getString(c.getColumnIndexOrThrow(StudentTable.COLUMN_AM)));
            student.setStudentName (c.getString(c.getColumnIndexOrThrow(StudentTable.COLUMN_NAME)));
            student.setStudentSemester (c.getString(c.getColumnIndexOrThrow(StudentTable.COLUMN_SEMESTER)));
            student.setStudentScore (c.getInt (c.getColumnIndexOrThrow(StudentTable.COLUMN_SCORE)));
            student.setStudentDate (c.getString(c.getColumnIndexOrThrow(StudentTable.COLUMN_DATE)));


            StudentList.add (student);
        } while (c.moveToNext());
    }
    c.close ();
    return StudentList;
}
/**  we have created a new method for reading all the Questions  from Question Table.    */
public List<Question> getAllQuestions() {
    List<Question> questionList = new ArrayList<>();
    db = getReadableDatabase ();

    /** Choose limit number of Random Questions */
    Cursor c = db.rawQuery("SELECT * FROM quiz_question ORDER BY RANDOM() LIMIT 3 ",null );


    if (c.moveToFirst()){
        do {
            Question question = new Question();
            question.setQuestion(c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_QUESTION)));
            question.setImage (c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_IMAGE)));
            question.setAnswer1(c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_ANSWER1)));
            question.setAnswer2(c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_ANSWER2)));
            question.setAnswer3(c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_ANSWER3)));

            question.setAnswer4(c.getString(c.getColumnIndexOrThrow(QuestionTable.COLUMN_ANSWER4)));
            question.setAnswerNum (c.getInt(c.getColumnIndexOrThrow(QuestionTable.COLUMN_ANSWERNUM)));
            questionList.add (question);
        } while (c.moveToNext());
    }
    c.close ();
    return questionList;
}

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

`

There should be 2 arguments in the method addScore() : the id of the student and the new score that you want to store in the table.

The new score must be saved in the ContentValues object and the id will be used as the last argument of the method update() .

Also, there is no need for a SELECT query.

Use this:

public static void addScore(int id, int studentScore) {
    ContentValues cv = new ContentValues();
    cv.put(DataContract.StudentTable.COLUMN_SCORE, studentScore);
    db.update(
        DataContract.StudentTable.TABLE_NAME1, 
        cv, 
        DataContract.StudentTable.COLUMN_ID +  " = ?", 
        new String[] {String.valueOf(id)}
    );
    db.close();
}

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