问题描述
我一直在阅读BaseColumns
]( https://Android中的developer.android.com/reference/android/provider/BaseColumns.html )来帮助构建数据库架构.
I've been reading up on BaseColumns
](https://developer.android.com/reference/android/provider/BaseColumns.html) in Android to help structure my database schema.
我知道_ID
是您必须创建自己的行的唯一标识符:
I know that _ID
is a unique identifier for the row that you have to create yourself:
protected static final String SQL_CREATE = "CREATE TABLE " + TABLE_NAME + "( " +
_ID + " INTEGER PRIMARY KEY AUTOINCREMENT" + ...;
我还读到_COUNT
用于引用表中的行数.
I also read that _COUNT
is used to refer to the number of rows in a table.
但是,当我尝试使用_COUNT
时,出现错误.这是我尝试过的:
However, when I tried using _COUNT
, I got an error. Here is what I tried:
SQLiteDatabase db = TimetableDbHelper.getInstance(context).getReadableDatabase();
Cursor cursor = db.query(
SubjectsSchema.TABLE_NAME,
new String[] {SubjectsSchema._COUNT},
null, null, null, null, null);
cursor.moveToFirst();
int count = cursor.getInt(cursor.getColumnIndex(SubjectsSchema._COUNT));
cursor.close();
return count;
我不确定这是否是使用它的正确方法,但是出现了这个错误:
I'm not sure whether or not this is the correct way to use it, but I got this error:
我应该如何使用_COUNT
?
推荐答案
在数据库中,_id
或_count
没有什么特别的.
In the database, there is nothing special about either _id
or _count
.
当表被定义为具有这样的列时,或者当查询显式计算它时,您的查询将返回_id
或_count
列.
Your queries return an _id
or _count
column when the table is defined to have such a column, or when the query explicitly computes it.
Android框架的许多对象都希望游标具有唯一的_id
列,因此有很多表对其进行定义.
Many objects of the Android framework expect a cursor to have a unique _id
column, so many tables define it.
在大多数地方,预计不会出现_count
,因此通常不实施.并且如果确实需要它,则可以使用子查询简单地计算出它,如下所示:
In most places, the _count
is not expected to be present, so it is usually not implemented. And if it is actually needed, it can simply be computed with a subquery, like this:
SELECT _id,
[other fields],
(SELECT COUNT(*) FROM MyTable) AS _count
FROM MyTable
WHERE ...
如果要查找自己的表的大小,则不需要使用_count
名称.您可以执行类似SELECT COUNT(*) FROM subjects
的查询,或者甚至更简单地使用帮助函数为您完成此操作.
If you want to find out the size of your own table, you are not required to use the _count
name; you can execute a query like SELECT COUNT(*) FROM subjects
, or, even simpler, use a helper function that does this for you.
这篇关于如何在BaseColumns中使用_COUNT个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!