#鸿蒙通关秘籍#如何在鸿蒙系统中创建并获取键值型数据库

HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
雪域狼ML

要在鸿蒙系统中创建并获取键值型数据库,首先需要获取一个KVManager实例来管理数据库对象。可以使用如下代码创建该实例:

typescript import { distributedKVStore } from '@kit.ArkData'; import { window } from '@kit.ArkUI'; import { UIAbility } from '@kit.AbilityKit'; import { BusinessError } from '@kit.BasicServicesKit';

let kvManager: distributedKVStore.KVManager | undefined = undefined;

export default class EntryAbility extends UIAbility { onCreate() { let context = this.context; const kvManagerConfig: distributedKVStore.KVManagerConfig = { context: context, bundleName: 'com.example.datamanagertest' }; try { kvManager = distributedKVStore.createKVManager(kvManagerConfig); console.info('Succeeded in creating KVManager.'); } catch (e) { let error = e as BusinessError; console.error(Failed to create KVManager. Code:${error.code},message:${error.message}); } } }

if (kvManager !== undefined) { kvManager = kvManager as distributedKVStore.KVManager; }

完成KVManager实例的创建后,使用以下代码获取键值型数据库:

typescript let kvStore: distributedKVStore.SingleKVStore | undefined = undefined; try { const options: distributedKVStore.Options = { createIfMissing: true, encrypt: false, backup: false, autoSync: false, kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, securityLevel: distributedKVStore.SecurityLevel.S1 }; kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options, (err, store: distributedKVStore.SingleKVStore) => { if (err) { console.error(Failed to get KVStore: Code:${err.code},message:${err.message}); return; } console.info('Succeeded in getting KVStore.'); kvStore = store; }); } catch (e) { let error = e as BusinessError; console.error(An unexpected error occurred. Code:${error.code},message:${error.message}); }

if (kvStore !== undefined) { kvStore = kvStore as distributedKVStore.SingleKVStore; }

分享
微博
QQ
微信
回复
2天前
相关问题
键值数据库跨设备数据同步demo
831浏览 • 1回复 待解决
键值数据库是否有做bundleName校验
1575浏览 • 1回复 待解决