鸿蒙Next开发中如何打开sqlite数据库
在鸿蒙Next开发中,如何正确打开SQLite数据库?具体需要导入哪些类或模块?能否提供一段示例代码说明初始化和打开数据库的完整流程?
2 回复
鸿蒙Next里打开SQLite?简单!用RdbStore就行,先创建配置对象,再调用getRdbStore()。记得在config.json里声明数据库权限,不然会像没带钥匙进自家门——干瞪眼!代码一写,数据库秒开,比点外卖还快!
更多关于鸿蒙Next开发中如何打开sqlite数据库的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在鸿蒙Next(HarmonyOS NEXT)开发中,打开SQLite数据库可以通过@ohos.data.relationalStore模块实现。以下是具体步骤和示例代码:
1. 导入模块
import relationalStore from '@ohos.data.relationalStore';
import UIAbility from '@ohos.app.ability.UIAbility';
2. 定义数据库配置
const config = {
name: 'test.db', // 数据库文件名
securityLevel: relationalStore.SecurityLevel.S1 // 安全级别
};
3. 获取RdbStore对象
在Ability的onCreate或具体方法中打开数据库:
let rdbStore;
relationalStore.getRdbStore(this.context, config, (err, store) => {
if (err) {
console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
return;
}
rdbStore = store;
console.info('Succeeded in getting RdbStore.');
});
完整示例(在Ability中):
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
const config = {
name: 'mydb.db',
securityLevel: relationalStore.SecurityLevel.S1
};
relationalStore.getRdbStore(this.context, config, (err, store) => {
if (err) {
console.error('Open database failed');
return;
}
// 数据库打开成功,可执行后续操作
console.info('Database opened successfully');
});
}
}
说明:
- 数据库位置:数据库文件会自动创建在应用的沙箱目录下
- 安全级别:S1~S4级别,根据数据敏感程度选择
- 异步操作:使用回调函数处理打开结果
注意:需要先在module.json5中声明ohos.permission.RELATIONAL_STORE权限。

