如何使用 Room 从游标获取数据
How to get data from cursor using Room
我正在使用此查询从使用 Room
的数据库中获取数据,但无法弄清楚此查询的 return 类型以及如何从该查询中获取数据
@Query("SELECT COUNT(Unit), Age as COUNT from test where Age in (1, 2, 3) and Unit in ("U5", "U6", "U4") group by Age")
我在 sqllite online 运行 时得到的输出如下图所示。所以它就像键值对。
第 1 步:修改查询以命名两条输出:
SELECT COUNT(Unit) as count, Age from test where Age in (1, 2, 3) and Unit in ("U5", "U6", "U4") group by Age
步骤 #2:创建与查询输出匹配的 POJO:
class AgeCounts {
public int count;
public int age;
}
第 3 步:拥有 DAO 方法(您的 @Query
将在其上执行)return 您的 POJO class 的 List
(例如,List<AgeCounts>
), 可能包含在响应式类型中(例如,LiveData<List<AgeCounts>>
、Single<List<AgeCounts>>
):
@Query("SELECT COUNT(Unit) as count, Age from test where Age in (1, 2, 3) and Unit in ("U5", "U6", "U4") group by Age")
List<AgeCounts> getAgeCounts();
我正在使用此查询从使用 Room
的数据库中获取数据,但无法弄清楚此查询的 return 类型以及如何从该查询中获取数据
@Query("SELECT COUNT(Unit), Age as COUNT from test where Age in (1, 2, 3) and Unit in ("U5", "U6", "U4") group by Age")
我在 sqllite online 运行 时得到的输出如下图所示。所以它就像键值对。
第 1 步:修改查询以命名两条输出:
SELECT COUNT(Unit) as count, Age from test where Age in (1, 2, 3) and Unit in ("U5", "U6", "U4") group by Age
步骤 #2:创建与查询输出匹配的 POJO:
class AgeCounts {
public int count;
public int age;
}
第 3 步:拥有 DAO 方法(您的 @Query
将在其上执行)return 您的 POJO class 的 List
(例如,List<AgeCounts>
), 可能包含在响应式类型中(例如,LiveData<List<AgeCounts>>
、Single<List<AgeCounts>>
):
@Query("SELECT COUNT(Unit) as count, Age from test where Age in (1, 2, 3) and Unit in ("U5", "U6", "U4") group by Age")
List<AgeCounts> getAgeCounts();