androidsqliteandroid-query

How to insert records if update query failed in sqlite android


I have a case, If my update query is failed due because there is no existing data in database. Then, I want to insert new record if not available already in database. I searched everywhere, But, i did not get a solution according my source code. Find the below code and tell me the solution. Thanks advance dude.

 SQLiteDatabase db = this.getWritableDatabase();
     ContentValues values = new ContentValues();
     values.put(PAGENUM, stepaObj.getPageno());
     values.put(SCORE, stepaObj.getScore());
     values.put(FIR, stepaObj.getFir());
     values.put(PENALTY, stepaObj.getPenalty());
     values.put(PUTTS, stepaObj.getPutts());
     values.put(PLAYED, stepaObj.getPalyed());
     values.put(SCORECARDID, stepaObj.getScorecardid());
     values.put(ISUPDATE, stepaObj.getIsupdate());

     int result = db.update(TABLE_SCORECARD_STEPA, values, SCORECARDID+" = ?",
                new String[] { String.valueOf(scorecardID)});

     System.out.println("updateScore by API data = "+result);

     db.close(); 

Solution

  • If the update failed then the result will be 0 ( result : number of rows affected by update)

    int result = db.update(TABLE_SCORECARD_STEPA, values, SCORECARDID+" = ?",
                new String[] { String.valueOf(scorecardID)});
    
    if(result <= 0){
    
         result = db.insert(TABLE_SCORECARD_STEPA, null values);
    
    }