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

旋转门123
发布于 2025-3-28 14:39
1300浏览
0收藏

前言

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

一、环境准备

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

"requestPermissions": [
  {
    "name": "ohos.permission.DISTRIBUTED_DATASYNC"
  }
]
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

二、数据库初始化

1. 创建数据库和表

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

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)}`);
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

关键点说明:

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

三、CRUD操作实现

1. 插入数据(Create)

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');
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

2. 查询数据(Read)

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];
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.

3. 更新数据(Update)

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');
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

4. 删除数据(Delete)

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');
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.

四、UI界面实现

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

@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)
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.

五、总结

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

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

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

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
标签
收藏
回复
举报


回复
    相关推荐