鸿蒙关系数据库代码案例

复制代码
鸿蒙关系数据库代码案例,单页写完,便于新手入门学习!

// Index.ets
import relationalStore from '@ohos.data.relationalStore';
import common from '@ohos.app.ability.common';

// 数据表常量
const TABLE_NAME = "user";
const DB_NAME = "PracticeDB.db";
const DB_CONFIG: relationalStore.StoreConfig = {
  name: DB_NAME,
  securityLevel: relationalStore.SecurityLevel.S1
};

// 用户实体
interface User {
  id?: number;
  name: string;
  age: number;
}

@Entry
@Component
struct RdbCurdDemo {
  @State userList: User[] = [];
  @State inputName: string = "";
  @State inputAge: number = 18;
  rdbStore: relationalStore.RdbStore | null = null;
  ctx: common.UIAbilityContext | null = null;

  aboutToAppear() {
    this.ctx = getContext(this) as common.UIAbilityContext;
    this.initDB();
  }

  // 初始化数据库、创建表
  async initDB() {
    if (!this.ctx) return;
    try {
      this.rdbStore = await relationalStore.getRdbStore(this.ctx, DB_CONFIG);
      const createSql = `CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        age INTEGER
      )`;
      await this.rdbStore.executeSql(createSql);
      console.info("数据库初始化成功");
      this.queryAll();
    } catch (err) {
      console.error("初始化失败:", JSON.stringify(err));
    }
  }

  // 【CREATE】新增
  async insertUser() {
    if (!this.rdbStore || !this.inputName) return;
    const valueBucket: relationalStore.ValuesBucket = {
      name: this.inputName,
      age: this.inputAge
    };
    try {
      const rowId = await this.rdbStore.insert(TABLE_NAME, valueBucket);
      console.info("新增成功 rowId:", rowId);
      this.queryAll();
    } catch (e) {
      console.error("新增失败", e);
    }
  }

  // 【READ】查询全部(修复重点:使用RdbPredicates)
  async queryAll() {
    if (!this.rdbStore) return;
    let resultSet: relationalStore.ResultSet | null = null;
    try {
      // ✅ 正确写法:构造查询条件对象,不再直接传表名字符串
      const predicates = new relationalStore.RdbPredicates(TABLE_NAME);
      resultSet = await this.rdbStore.query(predicates, ["id", "name", "age"]);

      const list: User[] = [];
      // !非空断言,resultSet这里一定有值
      while (resultSet.goToNextRow()) {
        list.push({
          id: resultSet.getLong(0),
          name: resultSet.getString(1),
          age: resultSet.getLong(2)
        });
      }
      this.userList = list;
    } catch (e) {
      console.error("查询失败", e);
    } finally {
      // 关闭游标
      if (resultSet !== null) {
        resultSet.close();
      }
    }
  }

  // 【UPDATE】修改
  async updateUser(userId: number, newName: string) {
    if (!this.rdbStore) return;
    const bucket: relationalStore.ValuesBucket = { name: newName };
    const predicates = new relationalStore.RdbPredicates(TABLE_NAME);
    predicates.equalTo("id", userId);
    try {
      const count = await this.rdbStore.update(bucket, predicates);
      console.info(`更新行数:${count}`);
      this.queryAll();
    } catch (e) {
      console.error("更新失败", e);
    }
  }

  // 【DELETE】删除
  async deleteUser(userId: number) {
    if (!this.rdbStore) return;
    const predicates = new relationalStore.RdbPredicates(TABLE_NAME);
    predicates.equalTo("id", userId);
    try {
      const delCount = await this.rdbStore.delete(predicates);
      console.info(`删除行数:${delCount}`);
      this.queryAll();
    } catch (e) {
      console.error("删除失败", e);
    }
  }

  build() {
    Column() {
      Text("RDB数据库 CURD 练习")
        .fontSize(24)
        .fontWeight(FontWeight.Bold)
        .margin({ bottom: 12 })

      Row() {
        TextInput({ text: this.inputName, placeholder: "姓名" })
          .width(120)
          .onChange((v: string) => this.inputName = v)
        TextInput({ text: this.inputAge.toString(), placeholder: "年龄" })
          .width(80)
          .margin({ left: 6 })
          .onChange((v: string) => {
            const num = Number(v);
            this.inputAge = isNaN(num) ? 0 : num;
          })
      }.margin({ bottom: 8 })

      Button("新增用户")
        .width("90%")
        .onClick(() => this.insertUser())

      Text("==== 用户列表 ====").margin({ top: 12 })

      List() {
        ForEach(this.userList, (item: User) => {
          ListItem() {
            Row() {
              Text(`ID:${item.id} ${item.name} ${item.age}岁`)
                .layoutWeight(1)
              Button("改名字")
                .fontSize(12)
                .margin({ right: 4 })
                .onClick(() => this.updateUser(item.id!, item.name + "_edit"))
              Button("删除")
                .fontSize(12)
                .backgroundColor("#dc3545")
                .onClick(() => this.deleteUser(item.id!))
            }
          }
        })
      }
      .width("100%")
      .height(300)
      .margin({ top: 8 })
    }
    .width("100%")
    .padding(16)
  }
}
相关推荐
梦想不只是梦与想7 小时前
鸿蒙AGC设备管理:设备注册(一)
harmonyos·设备管理·appgallery
熊猫钓鱼>_>8 小时前
鸿蒙ArkUI全手势操作实战指南:6大基础手势从原理到落地避坑
人工智能·深度学习·华为·架构·harmonyos·arkui·tapgesture
2501_9197490310 小时前
华为鸿蒙记录怀孕APP—小羊怀孕
华为·harmonyos·鸿蒙
YM52e12 小时前
鸿蒙 ArkTS 实战|网络常用漫剧主角名称分类表:26 位主角 8 大分类 + 搜索筛选
学习·华为·harmonyos
小雨青年13 小时前
【HarmonyOS 7 悬浮页签深度实战】02 从普通底栏到第一个悬浮页签
华为·harmonyos
whyutianict_vv13 小时前
从零到上架6款APP:AI鸿蒙全栈智能体开发5个月实战复盘(ArkTS/DevEco/AGC全流程)
人工智能·个人开发·harmonyos
OH_TPC14 小时前
HarmonyOS APP开发---"启动秀"应用引导页App,需要用到这个库
harmonyos
见山是山-见水是水15 小时前
围绕HTTP 网络请求实战构建原生体验:设计取舍、实现与排错
网络·网络协议·http·华为·harmonyos
见山是山-见水是水16 小时前
拆解网络缓存策略设计:原生鸿蒙页面的实现路径与调试方法
http·缓存·华为·harmonyos
蓝速科技16 小时前
蓝速鸿蒙信创终端长效流畅性深度评测
arm开发·华为·harmonyos