HarmonyOS关系型数据库操作指南:增删改查实战

前言

在HarmonyOS应用开发中,数据持久化是一个非常重要的环节。关系型数据库(RDB)提供了一种结构化的数据存储方式,非常适合存储需要频繁查询和操作的复杂数据。本文将详细介绍如何在HarmonyOS应用中使用@ohos.data.relationalStore模块进行数据库的增删改查操作。

一、环境准备

首先确保你的DevEco Studio已配置好HarmonyOS开发环境,并在module.json5文件中添加了必要的权限:

json 复制代码
"requestPermissions": [
  {
    "name": "ohos.permission.DISTRIBUTED_DATASYNC"
  }
]

二、数据库初始化

1. 创建数据库和表

我们首先需要初始化数据库并创建表:

typescript 复制代码
const SQL_CREATE_TABLE = `
  CREATE TABLE IF NOT EXISTS EMPLOYEE (
    ID INTEGER PRIMARY KEY AUTOINCREMENT,
    NAME TEXT NOT NULL,
    AGE INTEGER,
    SALARY REAL,
    Codes TEXT
  )`;

private async initRdbStore() {
  try {
    this.rdbStore = await relationalStore.getRdbStore(getContext(), {
      name:'harmonyos.db',
      securityLevel:relationalStore.SecurityLevel.S1
    });
    await this.rdbStore.executeSql(SQL_CREATE_TABLE);
    console.info('Table created successfully');
    this.query(); // 初始数据加载
  } catch (err) {
    console.error(`Database init failed: ${JSON.stringify(err)}`);
  }
}

关键点说明:

  • getRdbStore()方法用于获取或创建数据库
  • SecurityLevel.S1表示数据库安全级别
  • executeSql()用于执行SQL语句创建表

三、CRUD操作实现

1. 插入数据(Create)

javascript 复制代码
async insert() {
  if (!this.rdbStore) return;

  const employee: Employee = {
    id:null,
    name: 'zz',
    age: 18,
    salary: 100.86,
    Codes: '鸿蒙'
  };

  try {
    const rowId = await this.rdbStore.insert("EMPLOYEE", employee);
    console.info(`Insert success, rowId: ${rowId}`);
    employee.id = rowId;
    this.employees = [...this.employees, employee];
  } catch (err) {
    this.handleError(err as BusinessError, 'Insert');
  }
}

2. 查询数据(Read)

typescript 复制代码
async query() {
  if (!this.rdbStore) return;

  const predicates = new relationalStore.RdbPredicates("EMPLOYEE");
  const columns = ["ID", "NAME", "AGE", "SALARY", "Codes"];

  try {
    const resultSet = await this.rdbStore.query(predicates, columns);
    this.processResultSet(resultSet);
  } catch (err) {
    this.handleError(err as BusinessError, 'Query');
  }
}

private processResultSet(resultSet: relationalStore.ResultSet) {
  const temp: Employee[] = [];
  if (resultSet.rowCount > 0) {
    while (resultSet.goToNextRow()) {
      temp.push({
        id: resultSet.getLong(0),
        name: resultSet.getString(1),
        age: resultSet.getLong(2),
        salary: resultSet.getDouble(3),
        Codes: resultSet.getString(4)
      });
    }
  }
  resultSet.close(); // 必须关闭结果集
  this.employees = [...temp];
}

3. 更新数据(Update)

javascript 复制代码
async update() {
  if (!this.rdbStore) return;

  const updateValues : ValuesBucket= {
    Codes: 'Java' // 只更新需要的字段
  };

  const predicates = new relationalStore.RdbPredicates("EMPLOYEE");
  predicates.equalTo('NAME', 'zz');

  try {
    const affectedRows = await this.rdbStore.update(updateValues, predicates);
    console.info(`Updated ${affectedRows} rows`);
    this.query();
  } catch (err) {
    this.handleError(err as BusinessError, 'Update');
  }
}

4. 删除数据(Delete)

javascript 复制代码
async remove() {
  if (!this.rdbStore) return;

  const predicates = new relationalStore.RdbPredicates("EMPLOYEE");
  predicates.equalTo("ID", 2); // 删除ID为2的记录

  try {
    const affectedRows = await this.rdbStore.delete(predicates);
    console.info(`Deleted ${affectedRows} rows`);
    this.query(); // 删除后刷新
  } catch (err) {
    this.handleError(err as BusinessError, 'Delete');
  }
}

四、UI界面实现

我们使用ArkUI构建了一个简单的界面来展示操作按钮和数据表格:

scss 复制代码
@Builder
buildActionButtons() {
  Row() {
    Button('添加')
      .onClick(() => this.insert())
      .type(ButtonType.Capsule)

    Button('删除')
      .onClick(() => this.remove())
      .type(ButtonType.Capsule)
      .margin({ left: 10 })

    Button('修改')
      .onClick(() => this.update())
      .type(ButtonType.Capsule)
      .margin({ left: 10 })

    Button('查看')
      .onClick(() => this.query())
      .type(ButtonType.Capsule)
      .margin({ left: 10 })
  }
  .justifyContent(FlexAlign.Center)
  .margin({ bottom: 20 })
}

@Builder
buildDataTable() {
  Column() {
    // 表头
    this.buildTableHeader()

    // 数据行
    List({ space: 8 }) {
      ForEach(this.employees, (item: Employee) => {
        ListItem() {
          this.buildTableRow(item)
        }
      }, (item: Employee) => item.id?.toString() ?? '')
    }
    .layoutWeight(1)
    .divider({ strokeWidth: 1, color: Color.Gray })
  }
  .borderRadius(8)
  .border({ width: 1, color: Color.Gray })
  .padding(8)
}

五、总结

本文详细介绍了HarmonyOS关系型数据库的CRUD操作,包括:

  • 数据库和表的创建
  • 数据的插入、查询、更新和删除
  • 使用RdbPredicates构建查询条件
  • 结果集的遍历和处理
  • 完整的UI实现

通过这个示例,你可以快速掌握HarmonyOS中关系型数据库的基本操作,为开发数据驱动的应用打下坚实基础。

相关推荐
李游Leo11 分钟前
HarmonyOS:ComposeTitleBar 组件自学指南
harmonyos
抓鱼猫L19 分钟前
鸿蒙Next(四)文字识别
harmonyos
IT乐手1 小时前
3.7、HarmonyOS Next 自定义弹窗(CustomDialog)
harmonyos
李游Leo1 小时前
HarmonyOS:ArkTS 多态样式自学指南
harmonyos
zacksleo1 小时前
鸿蒙Flutter实战:20. Flutter集成高德地图,同层渲染
flutter·harmonyos
李游Leo1 小时前
HarmonyOS:ArkTS RowSplit 组件自学指南
harmonyos
NodeMedia1 小时前
如何快速集成NodeMediaClient-Harmony
harmonyos
IT乐手1 小时前
3.8、HarmonyOS Next 气泡提示(Popup)
harmonyos
zacksleo1 小时前
鸿蒙Flutter实战:19-Flutter集成高德地图,跳转页面方式
flutter·harmonyos
BensionLZ2 小时前
HO与OH差异之Navigation三
harmonyos