检查表中是否已存在数据,或检查表是否为空

时间:2010-08-06 14:34:05

标签: java android sqlite

朋友,    我在sqlite查询中需要帮助来检查数据是否已经存在于表中, 或者检查表是否为空,让我们对它进行查询。

提前致谢。

4 个答案:

答案 0 :(得分:2)

REFINED QUERY

  

SELECT TABLE(*)FROM TABLE WHERE   ROWNUM = 1

答案 1 :(得分:1)

SELECT COUNT(*) FROM `tableName`;

如果结果为0则表为空;)

答案 2 :(得分:1)

另请阅读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;
}

答案 3 :(得分:1)

试试这个,

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;
}

其中“mDb” - > SQLiteDatabase对象