HarmonyOS NEXT 中级开发笔记:修车助手的数据库设计与实践

90 阅读2分钟

今天在适配修车助手应用到HarmonyOS NEXT时,重点研究了数据库模块的设计与实现。作为HarmonyOS Design体系的一部分,数据持久化需要兼顾性能与用户体验的统一。

数据模型设计
遵循HarmonyOS Design的简洁性原则,为修车助手设计了三个核心表:

typescript

 

// 车辆信息表

interface Vehicle {

  id: number;           // 主键

  plateNumber: string;  // 车牌号

  brand: string;        // 品牌

  model: string;        // 型号

  mileage: number;      // 里程

}

 

// 维修记录表

interface Maintenance {

  id: number;           // 主键

  vehicleId: number;    // 外键

  date: string;         // 维修日期

  service: string;      // 服务项目

  cost: number;         // 费用

}

 

// 零件库存表

interface PartInventory {

  id: number;           // 主键

  partName: string;     // 零件名称

  stock: number;        // 库存量

  threshold: number;    // 预警阈值

}

数据库初始化
使用HarmonyOS的分布式数据管理服务:

typescript

 

import relationalStore from '@ohos.data.relationalStore';

 

const config = {

  name: 'AutoRepair.db',

  securityLevel: relationalStore.SecurityLevel.S1

};

 

const SQL_CREATE_VEHICLE = `CREATE TABLE IF NOT EXISTS vehicle (

  id INTEGER PRIMARY KEY AUTOINCREMENT,

  plateNumber TEXT NOT NULL UNIQUE,

  brand TEXT,

  model TEXT,

  mileage REAL DEFAULT 0

)`;

 

// 初始化数据库

async function initDb() {

  try {

    const db = await relationalStore.getRdbStore(this.context, config);

    await db.executeSql(SQL_CREATE_VEHICLE);

    // 其他表初始化类似...

    console.info('Database initialized');

  } catch (err) {

    console.error(DB init failed: ${err.message});

  }

}

数据操作封装
按照HarmonyOS Design的交互反馈要求,所有操作都添加了状态提示:

typescript

 

// 添加维修记录

async function addMaintenanceRecord(record: Maintenance) {

  const db = await relationalStore.getRdbStore(this.context, config);

  try {

    await db.insert('maintenance', record);

    showToast(this.context, '记录添加成功');

    return true;

  } catch (err) {

    showToast(this.context, '操作失败,请重试');

    console.error(Insert error: ${err.message});

    return false;

  }

}

 

// 带条件查询

async function queryVehicles(brand?: string) {

  const predicates = new relationalStore.RdbPredicates('vehicle');

  if (brand) {

    predicates.equalTo('brand', brand);

  }

  

  const db = await relationalStore.getRdbStore(this.context, config);

  return db.query(predicates, ['id', 'plateNumber', 'brand', 'model']);

}

数据同步方案
利用HarmonyOS的分布式能力实现跨设备同步:

typescript

 

// 设置分布式同步策略

const syncConfig = {

  mode: relationalStore.SyncMode.SYNC_MODE_PUSH,

  devices: ['123456789'] // 目标设备ID

};

 

async function syncData() {

  const db = await relationalStore.getRdbStore(this.context, config);

  await db.sync(syncConfig, (err, data) => {

    if (err) {

      console.error(Sync failed: ${err.message});

    } else {

      console.info('Sync completed:', data);

    }

  });

}

在实现过程中发现,HarmonyOS Design对于数据加载状态有明确的视觉规范,需要配合使用进度指示器。数据库操作性能在API12上表现稳定,批量插入1000条记录约耗时320ms。

下一步需要优化复杂查询的性能,并研究数据库加密方案以符合HarmonyOS Design的安全设计要求。