Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android record exists() in database?

Tags:

I am looking to the fastest and the correct way to check if a record exists in the database:

public boolean Exists(String _id) {     Cursor c=db.query(TABLENAME(), new String[] {"1"}, "_ID="+_id, null, null, null, null);     if (!c.equals(null))         return c.moveToFirst();     return false; } 

Do you see any problem with it?

like image 408
Pentium10 Avatar asked Mar 04 '10 13:03

Pentium10


2 Answers

Consider that mDb is your SqlLiteDatabase class

public boolean Exists(String _id) {    Cursor cursor = mDb.rawQuery("select 1 from yourTable where _id=%s",          new String[] { _id });    boolean exists = (cursor.getCount() > 0);    cursor.close();    return exists; } 
  • I keep your parameter _id as a String but I think it should be a Long.
  • select 1 is more fast than select columnName because the process doesn't need to retrieve all values from the table in the select clause.
  • you can put the string select 1 from... in a static final constant to be even faster.
like image 109
tbruyelle Avatar answered Sep 19 '22 15:09

tbruyelle


Since you are looking for an answer from 'credible and/or official sources', here in DatabaseUtils we have a method called queryNumEntries.

So your method could be made like this:

public boolean Exists(String _id) {     return DatabaseUtils.queryNumEntries(db, TABLENAME(), "_ID=?", new String[] {"1"}) > 0; } 

Or, for faster one:

public boolean Exists(String _id) {     return DatabaseUtils.longForQuery(db, "select count(*) from " + TABLENAME() + " where _ID=? limit 1", new String[] {"1"}) > 0; } 
like image 34
Randy Sugianto 'Yuku' Avatar answered Sep 19 '22 15:09

Randy Sugianto 'Yuku'