For my application, I am trying to add entries without having a duplicate entry, and if there are a duplicate notify the user and have him try again. Using SQLite, which I know very very little about, I have tried these two ways and want to know which one is better, more efficient or a better way to develop it?
First way:
db.execSQL("INSERT INTO " + DatabaseHelper.DATABASE_TABLE +
"(LATITUDE, LONGITUDE, RATING) SELECT " + latitude + ", " + longitude + ", " + rating +
" WHERE NOT EXISTS (SELECT 1 FROM " + DatabaseHelper.DATABASE_TABLE +
" WHERE LATITUDE = " + latitude + " AND LONGITUDE = " + longitude + ")");
Second way:
long id = -1;
try {
id = db.compileStatement(
"SELECT COUNT(*) FROM " + DatabaseHelper.DATABASE_TABLE
+ " WHERE LATITUDE = " + latitude
+ " AND LONGITUDE = " + longitude)
.simpleQueryForLong();
} catch (NullPointerException e) {
return -1;
}
return id;
The first way, either inserts or ignores the values, I check by doing so, storing the row-count of the rows into a variable before the call, call that function, and then check its results. If the results is not higher than it was before the call, the insert was made ignored, prompt the user with the ‘values exist’ message. (Very sloppy, I know but desperate times calls for desperate measures)
The second way, returns the actual count of rows that match the numbers I want to store, if the number returned greater than 1, prompt the user with the ‘values exist’ message.
I have been going back and forth, trying different ways but I do not know how to set up SQLite to have UNIQUE pairs, which I was told would be the easiest. If anyone can correct either of these ways and/or comment on them, that’d be greatly appreciated.
Thanks
I have decided to go with my second approach (see above)
Reason being since creating a
UNIQUE INDEXseem to not to work for me and proved to be a difficult task for me to accomplish whether that was result from my or SQLite’s end.It’s purpose is not trivial, approach may be elementary but it does what I need it to do.
I hope people encountering a situation like this can be influenced by the answers left here and wish they have better luck with it than I had.