2012-10-01 59 views
1

我想检查值是否存在于列中。例如,我想检查列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): [email protected]

我也尝试过使用:

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

,但我得到了同样的结果。

所以我希望对你有所帮助。

回答

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 
} 
+0

Upvote for'if(getStar.getCount()> 0)'。 – Sam

+0

非常感谢您的帮助。有用。 – Sabre

+0

第一种解决方案也适用。至少当没有值存在和何时只存在1个值时。 – Sabre

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 
+0

让我纠正你。 'artId'是一个列名不是值 – Sabre

+0

的权利,我已经更新了我的代码 – florianmski

1

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

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

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

相关问题