如何检查列中是否存在特定值?

时间:2012-10-01 19:18:42

标签: android sqlite cursor

我正在尝试检查列中是否存在该值。例如,我想检查列artId是否包含一些数值。我正在使用以下代码:

getStar = db.query(TABLE_NAME, new String[] { "artId" },
                        "artId = " + entryId, null, null,
                        null, null);
        getStar.moveToFirst();
        String star = getStar.toString();
        Log.w("ID COUNT", star);
        if(getStar != null) {
            // do something
        }

其中entryId是某个数字。

但我总是得到这样的东西:

W/ID COUNT(11303): android.database.sqlite.SQLiteCursor@41aa4c80

我也尝试使用:

getStar = db.rawQuery("SELECT count(*) FROM "
+ TABLE_NAME + " WHERE artId = '" + entryId + "'", null);

但我得到了同样的结果。

所以我希望得到你的帮助。

3 个答案:

答案 0 :(得分:5)

Cursor有效(非null),是的,因为它没有错误。检查它是否有任何数据。

getStar = db.rawQuery("SELECT count(*) FROM " + TABLE_NAME + " WHERE artId = '" + entryId + "'", null);
getStar.moveToFirst();
if (getStar.getInt(0)) { // This will get the integer value of the COUNT(*)
    // It has data
}

我对上述结果有点不确定;相反,您可以查询结果的数量:

getStar = db.rawQuery("SELECT * FROM " + TABLE_NAME + " WHERE artId = '" + entryId + "'", null);
if (getStar.getCount() > 0) { // This will get the number of rows
    // It has data
}

答案 1 :(得分:1)

moveTofirst()方法尝试将光标移动到第一个位置(基于0),如果可以,则返回true。否则返回false。所以你可以这样做:

if (getStar.moveToFirst) {
// your code
} else {}

如果有值,if语句将被执行,否则它将不会

答案 2 :(得分:0)

您正在记录游标String表示,而不是列artId列的值。 要从光标中获取列artId的值,您必须这样:

int count = -1;
// if the cursor is not empty
if(getStar.moveTofirst())
    count = getStar.getInt(getStar.getColumnIndex("artId");

if(count != -1)
    // do something