通过键值型数据库实现数据持久化

通过键值型数据库实现数据持久化-应用数据持久化-ArkData(方舟数据管理)-应用框架 - 华为HarmonyOS开发者 (huawei.com)

将数据持久化封装成一个类   要在app.json5中找到bundleName

import { common } from '@kit.AbilityKit';
import { distributedKVStore } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
export  class KVStorageTool {
  static kvStore: distributedKVStore.SingleKVStore | undefined = undefined

  static init(context: common.UIAbilityContext) {
    let kvManager: distributedKVStore.KVManager | undefined = undefined;
    const kvManagerConfig: distributedKVStore.KVManagerConfig = {
      context: context,
      //在app.json5中找到bundleName
      bundleName: 'com.example.oa'
    };
    try {
      // 创建KVManager实例
      kvManager = distributedKVStore.createKVManager(kvManagerConfig);
      console.info('Succeeded in creating KVManager.');
      // 继续创建获取数据库
      try {
        const options: distributedKVStore.Options = {
          createIfMissing: true,
          encrypt: false,
          backup: false,
          autoSync: false,
          // kvStoreType不填时,默认创建多设备协同数据库
          kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
          // 多设备协同数据库:kvStoreType: distributedKVStore.KVStoreType.DEVICE_COLLABORATION,
          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.');
            KVStorageTool.kvStore = store;
            // 请确保获取到键值数据库实例后,再进行相关数据操作
          });
      } catch (e) {
        let error = e as BusinessError;
        console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`);
      }
    } catch (e) {
      let error = e as BusinessError;
      console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`);
    }
  }

  static setData(key: string, val: string) {
    try {
      KVStorageTool.kvStore!.put(key, val, (err) => {
        if (err !== undefined) {
          console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
          return;
        }
        console.info('Succeeded in putting data.');
      });
    } catch (e) {
      let error = e as BusinessError;
      console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
    }
  }

  static getData(key: string,cb:(str:string)=>void) {
    KVStorageTool.kvStore?.get(key,(err,data)=>{
      //这个get里面可以书写逻辑
      cb(data as string)
    })
  }
  static getDataAsync(key:string):Promise<string>{
    return new Promise((r,j)=>{
      if(KVStorageTool.kvStore){
        KVStorageTool.kvStore?.get(key,(err,data)=>{
          if(err){
            r("")
          }
          r(data as string)
        })
      }else{
        r("")
      }
    })
  }
  static removeData(key:string){
    KVStorageTool.kvStore?.delete(key,(err)=>{
      if(err){
       promptAction.showToast({
         message:err.message
       })
        return
      }
    })

  }
}

在EntryAbility中添加代码

 onWindowStageCreate(windowStage: window.WindowStage): void {
    // Main window is created, set main page for this ability
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onWindowStageCreate');

    windowStage.loadContent('pages/Index', (err) => {
      if (err.code) {
        hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
        return;
      }
      hilog.info(0x0000, 'testTag', 'Succeeded in loading the content.');
    });
//添加
    KVStorageTool.init(this.context)
  }

在index里面使用

import { KVStorageTool } from '../tools/tool';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';
  @State token:string=''
  build() {
    RelativeContainer() {
      Text(this.message)
        .id('HelloWorld')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
      Button().onClick(()=>{
        KVStorageTool.setData("token","123")
        KVStorageTool.getData("token",(res)=>
        {
           this.token=res
        })
      })
      Text(this.token)
    }
    .height('100%')
    .width('100%')
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值