// 导入模块
import { distributedKVStore } from '@kit.ArkData';

// Stage模型
import { window } from '@kit.ArkUI';
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { Context } from '@ohos.abilityAccessCtrl';

// extends UIAbility
export default class KVStageUtils {
  // kvManager 代表数据库管理对象
  private kvManager: distributedKVStore.KVManager | undefined = undefined;
  //管理数据库里面数据列表
  private kvStore: distributedKVStore.SingleKVStore | undefined = undefined;
  private appId: string = 'com.example.homdbapplication';

  initKVStage(context: Context) {
    const kvManagerConfig: distributedKVStore.KVManagerConfig = {
      context: context,
      bundleName: this.appId
    };
    try {
      // 创建KVManager实例
      this.kvManager = distributedKVStore.createKVManager(kvManagerConfig);
      console.info('成功创建 KV 管理器');
    } catch (e) {
      let error = e as BusinessError;
      console.error(`创建 KV 管理器失败. Code:${error.code},message:${error.message}`);
    }
  }

  /**
   * 创建kv表
   */
  createKVStore(storeId: string) {
    try {
      const options: distributedKVStore.Options = {
        createIfMissing: true,
        encrypt: false,
        backup: false,
        autoSync: false,
        // kvStoreType不填时,默认创建多设备协同数据库
        kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
        // 多设备协同数据库:kvStoreType: distributedKVStore.KVStoreType.DEVICE_COLLABORATION,
        // schema未定义可以不填,定义方法请参考上方schema示例。
        securityLevel: distributedKVStore.SecurityLevel.S3
      };
      (this.kvManager as distributedKVStore.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.');
          this.kvStore = store;
        });
    } catch (e) {
      let error = e as BusinessError;
      console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
    }
  }

  /**
   * 插入数据
   */
  insertKVData(key: string, value: string) {
    try {
      (this.kvStore as distributedKVStore.SingleKVStore).put(key, value, (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}`);
    }
  }

  /**
   * 获取数据
   */
  getKVData(key: string) {
    return new Promise<string | number | boolean | Uint8Array>((resolve, reject) => {
      (this.kvStore as distributedKVStore.SingleKVStore).get(key, (err, data) => {
        if (err != undefined) {
          reject(err)
        }
        console.log("获取到结果" + data)
        resolve(data)
      });
    })
  }

  /**
   * 删除数据
   */
  deleteKVData(key: string) {
    (this.kvStore as distributedKVStore.SingleKVStore).delete(key, (err) => {
      if (err !== undefined) {
        console.error(`Failed to delete data. Code:${err.code},message:${err.message}`);
        return;
      }
    });
  }
}

const kvStageUtils = new KVStageUtils()

export { kvStageUtils }

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/data-persistence-by-kv-store#%E5%BC%80%E5%8F%91%E6%AD%A5%E9%AA%A4

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐