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

后端 未结 13 1516
情话喂你
情话喂你 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:25
    public boolean isEmpty(String TableName){
    
    SQLiteDatabase database = this.getReadableDatabase();
    return (int) DatabaseUtils.queryNumEntries(database,TableName) == 0;
    }
    
    0 讨论(0)
  • 2020-12-01 13:26

    you mean if it has record right ? i've tried this and for me it's work

        dbCur = db.rawQuery("select * from player", null);
        Log.e("a", ""+dbCur.getCount());
    

    it will show the sum of the table, if the table doesn't have record, then it will show 0.

    0 讨论(0)
  • 2020-12-01 13:35

    Use this:

    public Boolean doesRecordExist(String TableName, String ColumnName, String ColumnData) {
        String q = "Select * FROM "+TableName+" WHERE "+ColumnName+"='"+ColumnData+"';";
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(q, null);
        if (cursor.moveToFirst()) {
            return true;
        } else {
            return false;
        }
    }
    


    Example

    if (doesRecordExist("student", "name", "John") == true)
     {
     //Do Something
     } else { //Do something
     }
    

    Modify This according to your usage:

    String q = "Select * FROM "+TableName+" WHERE "+ColumnName+"='"+ColumnData+"';";
    
    0 讨论(0)
  • 2020-12-01 13:36

    Here's what I did...

    Cursor cur = db.rawQuery("SELECT count(*) FROM " + SQLHelper.TABLE_CART, null);
    if (cur != null && cur.moveToFirst() && cur.getInt(0) > 0) {
        Log.i(getClass().getName(), "table not empty");
    } 
    else {
        Log.i(getClass().getName(), "table is empty");
    }
    
    0 讨论(0)
  • 2020-12-01 13:37

    for java programs this worked for me:

        ResultSet rst = stm.executeQuery("SELECT * from Login");
               int i = 0;
               while(rst.next()){
                   ++i;
                   System.out.println(i);
               }
               System.out.println(i);
               if(i<1){
                   //No data in the table
               }
               else{
                   //data exists
               }
    
    0 讨论(0)
  • 2020-12-01 13:38

    What about this query?

    SELECT CASE WHEN EXISTS (SELECT * FROM CAT_BUD_TAB) THEN 1 ELSE 0 END
    

    It's slightly faster that SELECT COUNT(*).

    P.S. Checked on tables with 9 million rows.

    0 讨论(0)
提交回复
热议问题