tags:

views:

43

answers:

1

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?

+1  A: 

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 the retrieve a value from the table in the select clause.
  • you can put the string select 1 from... in a static final constant to be even faster.
kosokund
arf you have change your question while I was answering...
kosokund
thanks for your answer
Pentium10
you should also close the cursor before returning a value. it doesn't cause a crash but it does give warnings.
Al
yes you're right, I've updated my answer
kosokund