鸿蒙 应用数据持久化

200 阅读3分钟

应用数据持久化

应用数据持久化概述-应用数据持久化-数据管理-开发 | 华为开发者联盟 (huawei.com)

  • 用户首选项(Preferences) :通常用于保存应用的配置信息。数据通过文本的形式保存在设备中,应用使用过程中会将文本中的数据全量加载到内存中,所以访问速度快、效率高,但不适合需要存储大量数据的场景。
  • 键值型数据库(KV-Store) :一种非关系型数据库,其数据以“键值”对的形式进行组织、索引和存储,其中“键”作为唯一标识符。适合很少数据关系和业务关系的业务数据存储,同时因其在分布式场景中降低了解决数据库版本兼容问题的复杂度,和数据同步过程中冲突解决的复杂度而被广泛使用。相比于关系型数据库,更容易做到跨设备跨版本兼容。
  • 关系型数据库(RelationalStore) :一种关系型数据库,以行和列的形式存储数据,广泛用于应用中的关系型数据的处理,包括一系列的增、删、改、查等接口,开发者也可以运行自己定义的SQL语句来满足复杂业务场景的需要。

1.@ohos.data.preferences (用户首选项)

import common from '@ohos.app.ability.common';
import dataPreferences from '@ohos.data.preferences'

@Entry
@Component
struct Demo {
  private  context = getContext(this) as common.UIAbilityContext;//应用上下文
  private preferences;
  //存
  async save(key:string,value:string){
    if(!this.preferences) return false
    await this.preferences.put(key, value)//添加
    await this.preferences.flush();//持久化
    console.log('save成功')
  }
  //取
 async getval(key:string){
   if(!this.preferences) return false
   try{
     const val = await this.preferences.get(key,' ');//获取
     console.log('val'+val)
     return val
   }catch (e){
     console.log('读取出错')
   }
  }
  async delval(key:string){
    await this.preferences.delete(key)//删除
    console.log('删除成功')
  }
  aboutToAppear(){
    try {
      dataPreferences.getPreferences(this.context, 'mystore', (err, preferences) => {
        if (err) {
          console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
          return;
        }
        console.info('Succeeded in getting preferences.');
        this.preferences=preferences
        // 进行相关数据操作
      })
    } catch (err) {
      console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
    }
}
  build() {
    Column(){
      Button('存入数据').onClick(()=>this.save('abc','123121332'))
      Button('获取数据').onClick(()=>this.getval('abc'))
      Button('删除数据').onClick(()=>this.delval('abc'))
    }
}
}

2.@ohos.data.distributedKVStore (分布式键值数据库)

**distributedKVStore.createKVManager** 创建一个KVManager对象实例,用于管理数据库对象。

**KVManager**:分布式键值数据库管理实例,用于获取数据库的相关信息。
import distributedKVStore from '@ohos.data.distributedKVStore';
import common from '@ohos.app.ability.common'

@Entry
@Component
struct Index {  
  private  context = getContext(this) as common.UIAbilityContext;
  private  kvManager;
  private  kvStore

  async save(key:string, val: string){
    await this.kvStore.put(key,val)
    console.log('保存成功')
  }

  async getval(key:string){
    const val = await this.kvStore.get(key)
    console.log('读取的val是',val)
  }
  async del(key:string){
    await this.kvStore.delete(key)
    console.log('删除成功')
  }


  aboutToAppear(){//KVManager:分布式键值数据库管理实例,用于获取数据库的相关信息。
    this.kvManager = distributedKVStore.createKVManager({
      context: this.context,
      bundleName: 'com.example.datamanagertest'
    });

    const options = {
      createIfMissing: true, // 当数据库文件不存在时是否创建数据库,默认创建
      encrypt: false, // 设置数据库文件是否加密,默认不加密
      backup: false, // 设置数据库文件是否备份,默认备份
      kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, // 设置要创建的数据库类型,默认为多设备协同数据库
      securityLevel: distributedKVStore.SecurityLevel.S2 // 设置数据库安全级别
    };
    // storeId为数据库唯一标识符
    this.kvManager.getKVStore('storeId', options, (err, kvStore) => {
      if (err) {
        console.error(`Failed to get KVStore. Code:${err.code},message:${err.message}`);
        return;
      }
      console.info('Succeeded in getting KVStore.');
      this.kvStore = kvStore;
      // 进行相关数据操作
    });
  }

  build() {
    Column(){
      Button('存储').onClick(()=>this.save('abc','9527'))
      Button('读取').onClick(()=>this.getval('abc'))
      Button('删除').onClick(()=>this.del('abc'))

    }

  }
}