鸿蒙关系数据库代码案例,单页写完,便于新手入门学习!
// 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
相关推荐
安好说AI6 分钟前
Flutter 三方库 sound_mode 的鸿蒙化适配指南:免权限读取与受限写入的契约对齐●VON35 分钟前
Flutter 鸿蒙 disk_space_2 1.0.13 使用实战:下载前检查磁盘空间IT从业者张某某9 小时前
【鸿蒙PC命令行适配】GitUI 移植的工程实践:双 Git 引擎(libgit2/gitoxide)的鸿蒙适配之路lqj_本人9 小时前
WinPcap 鸿蒙 PC 适配全记录:从 NPF 原始抓包到 VPN_TUN 与 libpcap 双通路●VON10 小时前
Flutter 鸿蒙插件适配实战:用 device_screen_brightness 2.0.0 控制并监听屏幕亮度ChinaDragon10 小时前
HarmonyOS:应用横竖屏切换颜颜yan_10 小时前
ESP-IDF 鸿蒙 PC 适配全记录:打通 Python、构建工具链与 ESP32-P4 固件生成梦想不只是梦与想13 小时前
鸿蒙 邀请测试:AppGallery邀请测试流程贾伟康16 小时前
【口算王|02】HarmonyOS ArkTS 答题提交实战:防止重复提交并推进下一题承渊政道17 小时前
Python IDLE鸿蒙PC适配全记录:从Tkinter桌面程序到ArkUI原生开发闭环