Check if it contains Data in Sqlite table

Asked

Viewed 4,434 times

1

How to check if an Android Sqlite table contains data?

1 answer

2


There are two ways to do this:

Using a SELECT COUNT:

// Obtenha a instância de SQLiteDatabase
SQLiteDatabase db = ...;

Cursor cur = db.rawQuery("SELECT COUNT(*) FROM TABELA", null);

if (cur != null) {
    cur.moveToFirst();
    if (cur.getInt (0) == 0) {
        // Tabela esta vazia, preencha com seus dados iniciais
    } else {
        // Tabela ja contem dados.
    }
}

A recommendation for large tables can be the consultation:

SELECT EXISTS (SELECT 1 FROM TABELA)

In this query the engine can stop when finding the first element, being more performative.

Staying:

// Obtenha a instância de SQLiteDatabase
SQLiteDatabase db = ...;

Cursor cur = db.rawQuery("SELECT EXISTS (SELECT 1 FROM TABELA)", null);

if (cur != null) {
    cur.moveToFirst();
    if (cur.getInt (0) == 0) {
        // Tabela esta vazia, preencha com seus dados iniciais
    } else {
        // Tabela ja contem dados.
    }
}

Or using the DatabaseUtils:

// Obtenha a instância de SQLiteDatabase
SQLiteDatabase db = ...;
long numOfEntries = DatabaseUtils.queryNumEntries(db, "TABELA");

if(numOfEntries == 0l) {
    // Tabela vazia, preencha com seus dados iniciais
} else {
    // Tabela ja contem dados.
}

Looking at the source code of DatabaseUtils.queryNumEntries(SQLiteDatabase db, String table). They both do the same thing.

Sources:

  1. https://stackoverflow.com/questions/4397757/how-can-i-check-to-see-if-my-sqlite-table-has-data-in-it
  • because numOfEntries == 0l ? Wouldn’t 0?

  • The return of queryNumEntries is the type long, I just used the 0l (0 long) to avoid an implicit cast. Silly, you can use the 0 hassle-free.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.