android select count,如何使用SQLite在Android中获取查询的行数?

本文介绍了在Android应用中使用SQLite获取查询结果行数的多种解决方案,包括Cursor.getCount()、DatabaseUtils长期查询、rawQuery和字符串转换等技巧,帮助开发者解决计数问题并提高性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何使用SQLite在Android中获取查询的行数?

如何使用SQLite在Android中获取查询的行数? 看来我的以下方法无效。

public int getFragmentCountByMixId(int mixId) {

int count = 0;

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

Cursor cursor = db.rawQuery(

"select count(*) from downloadedFragement where mixId=?",

new String[]{String.valueOf(mixId)});

while(cursor.moveToFirst()){

count = cursor.getInt(0);

}

return count;

}

8个解决方案

105 votes

Cursor.getCount()

michaelg answered 2020-01-23T01:12:24Z

7 votes

cursor.moveToNext();

cursor.getCount();

如果未调用moveToNext(),则可能会出现cursorIndexOutOfBoundException。

Pramod Setlur answered 2020-01-23T01:12:44Z

4 votes

这将更加有效,因为适用于所有版本:

int numRows = DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM table_name", null);

要么

int numRows = DatabaseUtils.queryNumEntries(db, "table_name");

或者,如果您想获取特定选择的行数,则应该使用(在API 11中添加)

public static long queryNumEntries (SQLiteDatabase db, String table, String selection)

谢谢 :)

Pratik Butani answered 2020-01-23T01:13:17Z

1 votes

使用String而不是int

String strCount = "";

int count = 0;

SQLiteDatabase db = dbOpenHelper.getWritableDatabase();

Cursor cursor = db.rawQuery(

"select count(*) from downloadedFragement where mixId=?",

new String[]{String.valueOf(mixId)});

while(cursor.moveToFirst()){

strCount = cursor.getString(cursor.getColumnIndex("COUNT(*)"));

}

count = Integer.valueOf(strCount).intValue();

LK Yeung answered 2020-01-23T01:13:37Z

0 votes

查询表中的_ID列,然后在游标上调用getCount。 这是我在一个项目中正在做的链接。 查看行号110。

Gopal answered 2020-01-23T01:13:57Z

0 votes

在DatabaseUtils

public static long queryNumEntries(SQLiteDatabase db, String table)

James Wierzba answered 2020-01-23T01:14:16Z

0 votes

public long getRecords() {

return DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM contacts", null);

}

您可以将其用作方法,如果数据库使用自动增量,则可以使用此方法

public long getRecords() {

return DatabaseUtils.longForQuery(db, "SELECT seq FROM sqlite_sequence", null);

}

Rohit answered 2020-01-23T01:14:36Z

0 votes

val query = "SELECT * FROM $TABLE_NAME ;"

val result = db.rawQuery(query,null)

Toast.makeText(ctx,result.count,Toast.LENGTH_SHORT).show()

Stan answered 2020-01-23T01:14:52Z

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值