写点什么

HarmonyOS NEXT 中级开发笔记:家庭菜谱应用的数据库设计与实践

作者:bianchengyishu
  • 2025-03-31
    广东
  • 本文字数:1268 字

    阅读完需:约 4 分钟

今天在适配家庭菜谱应用到 HarmonyOS NEXT 时,重点研究了 HarmonyOS Design 规范下的数据持久化方案。基于 API12 的 @ohos.data.relationalStore 关系型数据库模块,记录几个关键实现点:

1. 数据库建模遵循 HarmonyOS Design 的"简洁高效"原则,设计了三张核心表:

typescript

// 数据库Schema定义  const SQL_CREATE_TABLE = `  CREATE TABLE IF NOT EXISTS recipe (      id INTEGER PRIMARY KEY AUTOINCREMENT,      name TEXT NOT NULL,      category TEXT CHECK(category IN ('中式','西式','日式')),      difficulty INTEGER DEFAULT 1  )  CREATE TABLE IF NOT EXISTS ingredient (      id INTEGER PRIMARY KEY,      recipe_id INTEGER,      name TEXT,      amount TEXT,      FOREIGN KEY (recipe_id) REFERENCES recipe(id) ON DELETE CASCADE  )`;  
复制代码

2. 数据库初始化

采用 HarmonyOS 推荐的异步事务处理:

typescript

import relationalStore from '@ohos.data.relationalStore';  
let rdbStore: relationalStore.RdbStore; const STORE_CONFIG = { name: "RecipeDB.db", securityLevel: relationalStore.SecurityLevel.S1 };
async function initDB() { try { rdbStore = await relationalStore.getRdbStore(this.context, STORE_CONFIG); await rdbStore.executeSql(SQL_CREATE_TABLE); console.info('Database initialized'); } catch (err) { console.error(`DB init failed: ${err.code}-${err.message}`); } }
复制代码

3. 数据操作封装

为符合 HarmonyOS Design 的流畅体验要求,对 CRUD 操作做了线程优化:

typescript

// 插入菜谱示例  async function insertRecipe(recipe: Recipe) {      const valueBucket = {          "name": recipe.name,          "category": recipe.category,          "difficulty": recipe.difficulty      };      try {          await rdbStore.insert("recipe", valueBucket);      } catch (err) {          console.error(`Insert failed: ${err.message}`);      }  }  
// 查询带食材的完整菜谱 async function getFullRecipe(recipeId: number) { const predicates = new relationalStore.RdbPredicates("recipe"); predicates.equalTo("id", recipeId); const recipe = await rdbStore.query(predicates, ["id","name"]);
const ingPredicates = new relationalStore.RdbPredicates("ingredient"); ingPredicates.equalTo("recipe_id", recipeId); const ingredients = await rdbStore.query(ingPredicates);
return { ...recipe, ingredients }; }
复制代码

遇到的问题

· 跨设备同步场景下需要结合 DistributedDataKit 扩展

· 大数据量分页查询时需注意 Predicates 的 skip/limit 设置

明天计划尝试用 @ohos.data.preferences 实现用户偏好存储,与主数据库配合使用。整个开发过程深刻感受到 HarmonyOS Design 在数据一致性方面的严谨要求。

用户头像

还未添加个人签名 2025-03-23 加入

还未添加个人简介

评论

发布
暂无评论
HarmonyOS NEXT 中级开发笔记:家庭菜谱应用的数据库设计与实践_HarmonyOS NEXT_bianchengyishu_InfoQ写作社区