开发者

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

开发者 https://www.devze.com 2022-12-14 07:22 出处:网络
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

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("data开发者_开发知识库baseTester", "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.


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


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


Try this

result = db.insertWithOnConflict("tablename ", null, cv, -1);

0

精彩评论

暂无评论...
验证码 换一张
取 消