鸿蒙关系数据库代码案例,单页写完,便于新手入门学习!
// 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
相关推荐
二流小码农7 小时前
鸿蒙开发:router组件升级,彻底告别手动配置威哥爱编程15 小时前
模拟面试智能体开发实战 09:把面试官装进手机,鸿蒙端聊天界面用 SSE 流式输出让回复逐字滚出来威哥爱编程15 小时前
模拟面试智能体开发实战 10:配置写死在代码里还怎么换服务端,把设置和简历做成界面可配、可存Sirius_Ji1 天前
# 一份鸿蒙原生支持硬解的 ffmpeg 开发基座贾伟康1 天前
HarmonyOS API 26 Navigation路由栈上限:stackSizeLimit、过载保护与容量观测江华森2 天前
把鸿蒙云手机调试的 5 个坑写成 Skill:12 项检查清单与报错决策树木木子222 天前
用华为云码道构建校园导航应用「新生通」:从需求分析到工程落地贾伟康2 天前
HarmonyOS API 26 Navigation 自适应模式:mode、分栏切换与窗口断点治理贾伟康2 天前
【转盘决定吧|07】HarmonyOS ArkTS 6.0.2.130 趣味题库:场景分类、随机选择与详情页解耦贾伟康2 天前
【电路实验模拟|03】HarmonyOS ArkTS 交通灯实战:用定时状态切换红黄绿灯