Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android:Is there a better way to insert and/or update a database entry?

I have a database containing a userId and a note. The user doesn't know if there already is a note in the DB so they write one and click the 'Submit' button. I want to insert this note if there is no note for the userId or update that userId's already existing note:

notesDb.open();
boolean updateResult = notesDb.updateMessage(
        userId,
        details_notes_input.getText().toString());

if(updateResult == true) {
    Log.d("databaseTester", "Updated entry into table");
} else {
    Log.d("databaseTester", "FAILED to update entry into table");
    long insertResult = notesDb.insertMessage(
            userId,
            details_notes_input.getText().toString());
    if(insertResult == -1){
        Log.d("databaseTester", "Failed to insert entry into table");
    } else {
        Log.d("databaseTester", "Inserted entry into table");
    }   
}
notesDb.close();

So, I'm pretty much attempting to 'update' an entry and if I fail then I attempt to 'insert' it. I don't know SQL very well, but I would think there would be a better way. Thanks.

like image 438
Jim D. Avatar asked Dec 16 '09 07:12

Jim D.


2 Answers

It sounds like you could use sqlite's REPLACE to solve this problem, using SQLiteDatabase.replace().

like image 177
Dan Lew Avatar answered Nov 01 '22 01:11

Dan Lew


You can catch a constraint exception launched in case of previous ID existence and then update.

try {
    db.insertOrThrow("sometable", null, cv);
} catch (SQLiteConstraintException e) {
    db.update("sometable", cv,"sometable_uid =" + id, null);
}
like image 32
Laranjeiro Avatar answered Nov 01 '22 01:11

Laranjeiro