Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
222 views
in Technique[技术] by (71.8m points)

java - Android record exists() in database?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...