How can i check to see if my sqlite table has data in it?

后端 未结 13 1675
情话喂你
情话喂你 2020-12-01 13:14

EDIT, Changed the code slightly based on answers below, but still haven\'t got it working. I also added a log message to tell me if getCount was returning > 0, and i

13条回答
  •  北海茫月
    2020-12-01 13:45

    The query SELECT COUNT(*) on an existing table should never return null. If there are no rows in the table, it should return one row containing the value zero.

    Conversely, a row with a non-zero value indicates that it's not empty.

    In both cases, one row should be returned, meaning that it will always go through the

    //do nothing everything's as it should be
    

    section.

    To fix it, leave your query as-is (you don't want to do select column_name simply because that would be unnecessary and possibly a little inefficient). Leave it as select count(*), which will always return one row, and use the following code (tested only in my head so be careful):

    Cursor cur = db.rawQuery("SELECT COUNT(*) FROM CAT_BUD_TAB", null);
    if (cur != null) {
        cur.moveToFirst();                       // Always one row returned.
        if (cur.getInt (0) == 0) {               // Zero count means empty table.
            for (int i = 0; i < 13; i++) {
                db.execSQL (catInsertArray[i]);
            }
        }
    }
    

提交回复
热议问题