HarmonyOS鸿蒙NEXT中如何查询云数据库我的病虫害历史记录

HarmonyOS鸿蒙NEXT中如何查询云数据库我的病虫害历史记录

通过cloudDatabase.DatabaseZone.query方法查询云数据库中满足条件的数据记录。

打开MyPestPage.ets文件

  1. 定义存储区、查询条件变量
agDBZone:cloudDatabase.DatabaseZone | undefined=undefined; // 云数据库存储区
condition:cloudDatabase.DatabaseQuery<cloudDatabase.DatabaseObject> | undefined=undefined; // 查询条件
  1. 初始化
aboutToAppear(): void {
    // 初始化云数据库
    this.agDBZone = cloudDatabase.zone('NMSS');
    // 先查询首选项中的用户ID,用户手机号登录之后
    this.getMyPest('18886668888');
}
  1. 获取我的病虫害诊断历史记录
/**
 * 获取用户诊断历史记录
 * @param userId 用户ID
 */
async getMyPest(userId:string):Promise<void>{
    this.condition=new cloudDatabase.DatabaseQuery(Pest);
    this.condition.equalTo('UserId',userId).orderByDesc('UpdateDate');
    this.agDBZone?.query(this.condition)
      .then(result=>{
        let ps:Pest[] =result as Pest[];
        ps.forEach(item:Pest)=>{
          let pest:Pest =item as Pest;
          let model:PestModel =new PestModel();
          model.ID=pest.ID;
          model.AGID=pest.AGID;
          model.Type=pest.Type;
          model.ImgUri=pest.Img;
          model.PestName=pest.PestName;
          model.PestCtrl=pest.PestCtrl;
          this.myPests.push(model);
        });
      })
      .catch(err:BusinessError)=>{
        // 无任何操作
      }
}

注意:数据记录的唯一性,根据当前登录的用户ID(手机号)。


更多关于HarmonyOS鸿蒙NEXT中如何查询云数据库我的病虫害历史记录的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS NEXT中查询云数据库的病虫害历史记录,需使用@ohos.data.cloud云数据库API。具体步骤:

  1. 初始化云数据库:
import cloud from '@ohos.data.cloud';
const store = await cloud.createCloudZone("yourZoneName");
  1. 构建查询条件:
const query = new cloud.Query();
query.equalTo("recordType", "pest");
query.orderByDesc("createTime");
  1. 执行查询:
const result = await store.executeQuery("yourCollection", query);

注意需先在AppGallery Connect配置云数据库,并在manifest.json中声明所需权限。查询结果会以JSON数组形式返回。

更多关于HarmonyOS鸿蒙NEXT中如何查询云数据库我的病虫害历史记录的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS NEXT中查询云数据库的病虫害历史记录,你的代码实现基本正确。这里补充几个关键点:

  1. 确保已正确初始化云数据库服务,在config.json中配置好NMSS存储区。

  2. 查询条件构建时,建议添加分页限制避免数据量过大:

this.condition.limit(20); // 限制返回20条记录
  1. 对于错误处理,建议至少添加日志记录:
.catch((err:BusinessError)=>{
  logger.error('查询病虫害记录失败:', err.code, err.message);
})
  1. 性能优化建议:
  • 如果数据量大,可考虑添加skip()实现分页
  • 考虑使用select()只查询需要的字段
  1. 确保Pest类与云数据库中的表结构完全匹配,特别是字段名和类型。

当前实现通过用户ID过滤并按更新时间降序排列,符合常见需求。如需进一步优化查询性能,可以在云数据库中为UserId和UpdateDate字段创建复合索引。

回到顶部