Check if data exists in the table, or check that the table is empty

friends, I need help with the sqlite query to check if the data exists in the table, or check the table is empty or not, give it answers.

Thanks in advance.

+3
source share
4 answers
SELECT COUNT(*) FROM `tableName`;

if the result is 0, the table is empty;)

+1
source

COMPLETED QUESTION

SELECT COUNT (*) FROM TABLE WHERE ROWNUM = 1

+2
source

Also kindly read DatabaseUtils .

/**
 * checks database if a column has a value in the table
 *
 * @param db
 * @param tableName
 * @param column
 * @param value
 * @param rowid to check against and skip if necessary
 * @return boolean
 */
public static boolean ExistsWithName(SQLiteDatabase db, String tableName, String column,
        String value, Long rowid) {
    String sql = String.format("select 1 from %s where %s = '%s'", tableName, column, value);
    if (rowid != null) {
        sql += " and _id != " + rowid;
    }
    Cursor c = null;
    Boolean ret = false;
    try {
        c = db.rawQuery(sql, null);
        if (c != null) {
            if (c.moveToFirst()) {
                ret = (c.getCount() > 0);
            } else {
                ret = false;
            }
        }
    } catch (Exception e) {
        Log.v(tableName, e.getMessage(), e);
        e.printStackTrace();
    } finally {
        if (c != null)
            c.close();
    }
    return ret;
}
+1
source

Try it,

public int getTableCount(String tableName) {

    int totalCount= 0;

    Cursor cur = mDb.rawQuery("SELECT COUNT(*) as count FROM " + tableName , null);

    if (cur != null) {
        cur.moveToFirst();
    }

    if (cur.moveToFirst()){
        do{
            totalCount = cur.getInt(cur.getColumnIndex("count"));
        }while(cur.moveToNext());
    }
    cur.close();

    return totalCount;
}

where "mDb" -> SQLiteDatabase object

+1
source

Source: https://habr.com/ru/post/1758407/


All Articles