首页 > 解决方案 > 如何使用 Room 从光标中获取数据

问题描述

我正在使用此查询从数据库中获取数据,Room但无法弄清楚此查询的返回类型以及如何从该查询中获取数据

@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 中运行时得到的输出如下图所示。所以它就像键值对。

在此处输入图像描述

标签: androidandroid-room

解决方案


步骤#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将使用的方法)返回List您的 POJO 类(例如,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();

推荐阅读