鸿蒙关系数据库代码案例,单页写完,便于新手入门学习!
// 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)
}
}
鸿蒙关系数据库代码案例
木合塔尔 麦麦提2026-08-05 11:17
相关推荐
云_杰1 小时前
鸿蒙截图工具开发实战 02:截屏权限 CUSTOM\_SCREEN\_CAPTURE——"检查"和"申请"为什么必须是两个函数nullregedit2 小时前
HarmonyOS 弦乐调音器开发实战 02:AudioCapturer 与 NSDF 怎样完成实时音高检测如此风景2 小时前
HarmonyOS应用开发-Navigation 路由表详解云端漫步19873 小时前
HarmonyOS NEXT AI 智能生活助手:AI 待办事项生成烛衔溟3 小时前
HarmonyOS 网络连接 —— HTTP 请求、Axios 与 Socket 通信懿路向前4 小时前
【HarmonyOS学习笔记】2026-08-04 | 端插件新装饰器与CreateRecord全链路验证云端漫步19874 小时前
HarmonyOS NEXT AI 智能生活助手:AI 翻译助手世人万千丶12 小时前
鸿蒙日志体系高级应用:HiLog分级输出/隐私脱敏/远程日志采集/线上问题精准溯源方案程序员黑豆18 小时前
鸿蒙应用开发:AttributeModifier 使用教程