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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With