多彩编程 多彩编程MZPH · CODE BLOG
ARTICLE DETAIL

文章详情

深耕前端与后端开发技术的一线实战笔记与踩坑复盘。

鸿蒙关系数据库代码案例

鸿蒙关系数据库代码案例 鸿蒙关系数据库代码案例单页写完便于新手入门学习// 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) } }
返回列表