Sqlite检查表是否为空

时间:2014-03-25 09:29:55

标签: android database sqlite

好吧,我有一个数据库,它有很多表。但通常表都是空的。 我想检查数据库表是否为空。 如果IF表为空,程序将填充它。

public static long queryNumEntries (SQLiteDatabase db, String table)

我会使用它,但它需要API 11.

6 个答案:

答案 0 :(得分:32)

您可以执行select count(*) from table并检查是否count> 0然后让其他人填充它。

 SQLiteDatabase db = table.getWritableDatabase();
String count = "SELECT count(*) FROM table";
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
if(icount>0)
//leave 
else
//populate table

答案 1 :(得分:8)

执行SELECT COUNT

boolean empty = true
Cursor cur = db.rawQuery("SELECT COUNT(*) FROM YOURTABLE", null);
if (cur != null && cur.moveToFirst()) {
    empty = (cur.getInt (0) == 0);
}
cur.close();

return empty;

答案 2 :(得分:6)

最佳解决方案

public boolean  isMasterEmpty() {

    boolean flag;
    String quString = "select exists(select 1 from " + TABLE_MASTERS  + ");";

    SQLiteDatabase db = getReadableDatabase();
    Cursor cursor = db.rawQuery(quString, null);
    cursor.moveToFirst();
    int count= cursor.getInt(0);
    if (count ==1) {
        flag =  false;
    } else {
        flag = true;
    } 
    cursor.close();
    db.close();

    return flag;
    }

答案 3 :(得分:6)

 public boolean isEmpty(String TableName){

    SQLiteDatabase database = this.getReadableDatabase();
    int NoOfRows = (int) DatabaseUtils.queryNumEntries(database,TableName);

    if (NoOfRows == 0){
        return true;
    }else {
        return false;
    }
}

答案 4 :(得分:1)

您可以这样做 -

if(checkTable("TABLE"))
{
  //table exists fill data.
}

检查表的方法 -

public static boolean checkTable(String table) {
Cursor cur2 = dbAdapter.rawQuery("select name from sqlite_master where name='"
        + table + "'", null);

if (cur2.getCount() != 0) {
    if (!cur2.isClosed())
        cur2.close();
    return true;
} else {
    if (!cur2.isClosed())
        cur2.close();
    return false;
}
}

答案 5 :(得分:0)

我认为,这个解决方案更好:

    boolean flag;

    DatabaseHelper databaseHelper = new DatabaseHelper(getApplicationContext(), DatabaseHelper.DATABASE_NAME, null, DatabaseHelper.DATABASE_VERSION);
    try {
        sqLiteDatabase = databaseHelper.getWritableDatabase();
    } catch (SQLException ex) {
        sqLiteDatabase = databaseHelper.getReadableDatabase();
    }
    String count = "SELECT * FROM table";
    Cursor cursor = sqLiteDatabase.rawQuery(count, null);
    if (cursor.moveToFirst()){
        flag = false;
    } else {
        flag = true;
    }
    cursor.close();
    sqLiteDatabase.close();

    return flag;

moveToFirst()检查表并返回true,如果表为空。标记正确的答案 - 使用额外检查。