如何计算Android中sqlite中的记录数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12436596/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count number of records in sqlite in Android
提问by user1602798
I am working on android project. I used sqlite database for it. I have tables in database. I have created databasehelper class. i want to count number of records in particular table. how can i achieve this ? any help will be appreciated?
我正在研究 android 项目。我为此使用了sqlite数据库。我在数据库中有表。我创建了 databasehelper 类。我想计算特定表中的记录数。我怎样才能做到这一点?任何帮助将不胜感激?
回答by Nick Bradbury
This would be more efficient:
这会更有效率:
int numRows = DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM table_name", null);
Or:
或者:
int numRows = DatabaseUtils.queryNumEntries(db, "table_name");
回答by user370305
Using SELECT COUNT(*) FROM table_name
query and, than count the size of Cursor..
使用SELECT COUNT(*) FROM table_name
查询和,而不是计算 Cursor 的大小..
The method from Cursor to count size (number of rows in cursor) is,
从 Cursor 计算大小(游标中的行数)的方法是,
getCount()
Returns the numbers of rows in the cursor.
返回游标中的行数。
OR:
或者:
From DatabaseUtilsuse method queryNumEntries(SQLiteDatabase db, String table)
从DatabaseUtils使用方法queryNumEntries(SQLiteDatabase db, String table)
Like,
喜欢,
long numberOfRows = DatabaseUtils.queryNumEntries(db, "table_name");
long numberOfRows = DatabaseUtils.queryNumEntries(db, "table_name");
which returns the number of rows in the table.
它返回表中的行数。
回答by Chirag
Try this.
尝试这个。
Cursor c = db.rawQuery("select * from your_table_name",null);
Log.i("Number of Records"," :: "+c.getCount());
Edit :c.getCount()returns the number of records of particular table.
编辑:c.getCount()返回特定表的记录数。
回答by Sam
In Kotlin
在科特林
fun getFruitTableCount(): Int {
val db = readableDatabase
val numRows = DatabaseUtils.longForQuery(db, "SELECT COUNT(*) FROM " + DBContract.FruitEntry.TABLE_NAME, null).toInt()
return numRows
}
回答by Victor USA
Please try this:
请试试这个:
In your DatabaseHelper.java:
在您的 DatabaseHelper.java 中:
public Cursor getYourTableContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + "Your table name", null);
return data;
}
To get the number of rows in your table:
要获取表中的行数:
Cursor yourCursor = myDB.getYourTableContents();
int i = 0;
while (yourCursor.moveToNext()) {
i += 1;
}
i
is your rows count as an integer.
i
是你的行算作一个整数。