0

I have two table (TABLE_EXAM,TABLE_RESULT). Here is value of my TABLE_RESULT.

result_id   exam_id   question_id   correct_answer  
  1            2            4              y     
  2            2            5              y       
  3            2            6              n         
  4            2            7              y        

I need to count how many correct_answer='y' where exam_id=2.
I try following code but it return 0.

public int calculateResult(int examId,String confirmAnswer)
{
    int correctAnswer=0;
    try
    {
        SQLiteDatabase db=this.getWritableDatabase();

         String selectQuery=("select count(correctAnswer) from result where exam_id ='" + examId + "' and correctAnswer ='" + 'y' +"'" );
        // String selectQuery=("SELECT COUNT(*)FROM result WHERE exam_id ='" + examId + "' and correctAnswer ='" + confirmAnswer +"'" );            
          Cursor cursor = db.rawQuery(selectQuery, null);
        if(cursor.moveToLast())
        {
            correctAnswer=cursor.getInt(3);
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return correctAnswer;
}

In variable confirm_answer i pass "y".
Give me some hint or reference.
Any help is appreciated.
Thanks in Advance

1 Answer 1

4
select count(*) from TABLE_RESULT where correct_answer="y" and exam id=2;

This is total number of rows which has value as y and exam id=2

Just try to run this query and then just Add your Parameters to it.

SELECT COUNT(*)FROM result WHERE exam_id =" + examId + " and correctAnswer ='" + confirmAnswer +"'");

Above is your query which i have formatted.

Hope this helps you.

Sign up to request clarification or add additional context in comments.

2 Comments

@sanpatil: i think your mistake was giving 2 as a string in the query which i have just removed.
Thanks...No,Actually i pass exam_id which contain value 2.... your 1st query is run on SQLite Browser but i need to check it in program.....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.