2012-04-27 71 views
0

我试过这个来得到行数。但该计划悬而未决。如何统计表中的行数?

private int countbaglist() 
{ 
    int count = 0; 
    SQLiteDatabase db = datasource.getWritableDatabase(); 
    Cursor cursor = db.rawQuery(
     "select count(*) from shoplist where itemname=?", 
     new String[] { String.valueOf("itemname") }); 

    while(cursor.moveToFirst()) 
    { 
     count = cursor.getCount(); 
    } 
    return count; 
} 

回答

2

因为您的while循环从不退出,所以它会挂起。改为将while替换为一次性的if。另外请注意,你需要阅读整数值COUNT查询返回,而不是光标的行数将始终为1

if (cursor.moveToFirst()) 
    count = cursor.getInt(0); 
+0

Downvoter,解释一下自己。我的答案是迄今为止唯一正确的答案。 – 2012-04-27 09:53:33

+0

my answr也corrent – 2012-04-27 09:55:00

+0

cursor.getInt(0);它是否在表中返回行号?或cursor.getCount();它是否在表中返回行号?解释它是如何工作的。 – Dinesh 2012-04-27 09:56:08

2

试试这个链接,你的答案

How to get the row count of a query in Android using SQLite?

删除下面的代码while条件:

while(cursor.moveToFirst()){ 
    count = cursor.getCount(); 
    } 

替换下面的代码:

​​
+0

'Cursor.getCount()'你不能调用方法与光标类本身,你必须创建它的对象 – 2012-04-27 09:48:49

+0

-1 cursor.getCount()将返回1(COUNT查询返回的行数),这是错误的。 – 2012-04-27 09:50:09

相关问题