Android record exists() in database?

前端 未结 6 1350
后悔当初
后悔当初 2020-12-13 10:00

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(TABLEN         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 10:37

    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;
    }
    

提交回复
热议问题