通过键值型数据库实现数据持久化 (ArkTS)
=======================

#### 场景介绍

键值型数据库存储键值对形式的数据，当需要存储的数据没有复杂的关系模型，比如存储商品名称及对应价格、员工工号及今日是否已出勤等，由于数据复杂度低，更容易兼容不同数据库版本和设备类型，因此推荐使用键值型数据库持久化此类数据。

#### 约束限制

*   设备协同数据库，针对每条记录，Key的长度≤896 Byte，Value的长度<4 MB。
    
*   单版本数据库，针对每条记录，Key的长度≤1 KB，Value的长度<4 MB。
    
*   每个应用程序最多支持同时打开16个键值型分布式数据库。
    
*   键值型数据库事件回调方法中不允许进行阻塞操作，例如修改UI组件。
    

#### 接口说明

以下是键值型数据库持久化功能的相关接口，更多接口及使用方式请见[分布式键值数据库](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-distributedkvstore)。

| 接口名称 | 描述 |
| :-- | :-- |
| createKVManager(config: KVManagerConfig): KVManager | 创建一个KVManager对象实例，用于管理数据库对象。 |
| getKVStore<T>(storeId: string, options: Options, callback: AsyncCallback<T>): void | 指定options和storeId，创建并得到指定类型的KVStore数据库。 |
| put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void | 添加指定类型的键值对到数据库。 |
| get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void | 获取指定键的值。 |
| delete(key: string, callback: AsyncCallback<void>): void | 从数据库中删除指定键值的数据。 |
| closeKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void | 通过storeId的值关闭指定的分布式键值数据库。 |
| deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void | 通过storeId的值删除指定的分布式键值数据库。 |

#### 开发步骤

1.  若要使用键值型数据库，首先要使用createKVManager()方法获取一个KVManager实例，用于管理数据库对象。示例代码如下所示：
    
    // 导入模块
    // 在pages目录下新建KvStoreInterface.ets
    import { distributedKVStore } from '@kit.ArkData';
    import { BusinessError } from '@kit.BasicServicesKit';
    import EntryAbility from '../entryability/EntryAbility';
    // Logger为hilog封装后实现的打印功能
    import Logger from '../common/Logger';
    
    let kvManager: distributedKVStore.KVManager | undefined = undefined;
    let kvStore: distributedKVStore.SingleKVStore | undefined = undefined;
    let appId: string = 'com.example.kvstoresamples';
    let storeId: string = 'storeId';
    // Stage模型context从EntryAbility.ets中获取
    const context = EntryAbility.getContext();
    
    // FA模型获取context
    import { featureAbility } from '@kit.AbilityKit';
    import { BusinessError } from '@kit.BasicServicesKit';
    
    let context = featureAbility.getContext();
    
    // 下面所有接口的代码都实现在KvInterface中
    export class KvInterface {
    }
    
    public CreateKvManager = (() => {
      Logger.info('CreateKvManager start');
      if (typeof (kvManager) === 'undefined') {
        const kvManagerConfig: distributedKVStore.KVManagerConfig = {
          bundleName: appId,
          context: context
        };
        try {
          // 创建KVManager实例
          kvManager = distributedKVStore.createKVManager(kvManagerConfig);
          Logger.info('Succeeded in creating KVManager.');
        } catch (err) {
          Logger.error(\`Failed to create KVManager. Code:${err.code},message:${err.message}\`);
        }
      } else {
        Logger.info ('KVManager has created');
      }
    })
    
2.  使用getKVStore()方法创建并获取键值数据库。示例代码如下所示：
    
    public GetKvStore = (() => {
      Logger.info('GetKvStore start');
      if (kvManager === undefined) {
        Logger.info('KvManager not initialized');
        return;
      }
      try {
        let child1 = new distributedKVStore.FieldNode('id');
        child1.type = distributedKVStore.ValueType.INTEGER;
        child1.nullable = false;
        child1.default = '1';
        let child2 = new distributedKVStore.FieldNode('name');
        child2.type = distributedKVStore.ValueType.STRING;
        child2.nullable = false;
        child2.default = 'zhangsan';
    
        let schema = new distributedKVStore.Schema();
        schema.root.appendChild(child1);
        schema.root.appendChild(child2);
        schema.indexes = \['$.id', '$.name'\];
        // 0表示COMPATIBLE模式，1表示STRICT模式。
        schema.mode = 1;
        // 支持在检查Value时，跳过skip指定的字节数，且取值范围为\[0,4M-2\]。
        schema.skip = 0;
    
        const options: distributedKVStore.Options = {
          createIfMissing: true,
          // 设置数据库加密
          encrypt: true,
          backup: false,
          autoSync: false,
          // kvStoreType不填时，默认创建多设备协同数据库
          kvStoreType: distributedKVStore.KVStoreType.SINGLE\_VERSION,
          // 多设备协同数据库：kvStoreType: distributedKVStore.KVStoreType.DEVICE\_COLLABORATION,
          schema: schema,
          // schema未定义可以不填，定义方法请参考上方schema示例。
          securityLevel: distributedKVStore.SecurityLevel.S3
        };
        kvManager.getKVStore<distributedKVStore.SingleKVStore>(storeId, options,
          (err, store: distributedKVStore.SingleKVStore) => {
            if (err) {
              Logger.error(\`Failed to get KVStore: Code:${err.code},message:${err.message}\`);
              return;
            }
            Logger.info('Succeeded in getting KVStore.');
            kvStore = store;
            // 请确保获取到键值数据库实例后，再进行相关数据操作
          });
      } catch (e) {
        let error = e as BusinessError;
        Logger.error(\`An unexpected error occurred. Code:${error.code},message:${error.message}\`);
      }
    })
    
3.  使用on()方法订阅分布式数据变化，如需关闭订阅分布式数据变化，调用[off('dataChange')](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-distributedkvstore#offdatachange)关闭。示例代码如下所示：
    
    public On = (() =>{
      Logger.info('On start');
      if(kvStore === undefined) {
        Logger.info('On: kvStore not initialized');
        return;
      }
      try {
        kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE\_TYPE\_ALL, (data) => {
          Logger.info(\`dataChange callback call data: ${data}\`);
        });
      } catch (e) {
        let error = e as BusinessError;
        Logger.error(\`An unexpected error occurred. code:${error.code},message:${error.message}\`);
      }
    })
    
4.  调用put()方法向键值数据库中插入数据。示例代码如下所示：
    
    public Put = (() => {
      Logger.info('Put start');
      if (kvStore === undefined) {
        Logger.info('Put: kvStore not initialized');
        return;
      }
      const KEY\_TEST\_STRING\_ELEMENT = 'key\_test\_string';
      // 如果未定义Schema则Value可以传其他符合要求的值。
      const VALUE\_TEST\_STRING\_ELEMENT = '{"id":0, "name":"lisi"}';
      try {
        kvStore.put(KEY\_TEST\_STRING\_ELEMENT, VALUE\_TEST\_STRING\_ELEMENT, (err) => {
          if (err !== undefined) {
            Logger.error(\`Failed to put data. Code:${err.code},message:${err.message}\`);
            return;
          }
          Logger.info('Succeeded in putting data.');
        });
      } catch (e) {
        let error = e as BusinessError;
        Logger.error(\`An unexpected error occurred. Code:${error.code},message:${error.message}\`);
      }
    })
    
    ![](https://contentcenter-vali-drcn.dbankcdn.cn/pvt_2/DeveloperAlliance_scene_100_1/92/v3/mzevBuCZTzSCRfYhEiKxqQ/note_3.0-zh-cn.png?HW-CC-KV=V1&HW-CC-Date=20260612T073241Z&HW-CC-Expire=86400&HW-CC-Sign=D5C0D0581CCDB625625C0B23304D89E1178541C622097A161C5CEB929AECCA18)
    
    当Key值存在时，put()方法会修改其值，否则新增一条数据。
    
5.  调用get()方法获取指定键的值。示例代码如下所示：
    
    public Get = (() => {
      Logger.info('Get start');
      if (kvStore === undefined) {
        Logger.info('Get: kvStore not initialized');
        return;
      }
      const KEY\_TEST\_STRING\_ELEMENT = 'key\_test\_string';
      try {
        kvStore.get(KEY\_TEST\_STRING\_ELEMENT, (err, data) => {
          if (err != undefined) {
            Logger.error(\`Failed to get data. Code:${err.code},message:${err.message}\`);
            return;
          }
          Logger.info(\`Succeeded in getting data. Data:${data}\`);
        });
      } catch (e) {
        let error = e as BusinessError;
        Logger.error(\`Failed to get data. Code:${error.code},message:${error.message}\`);
      }
    })
    
6.  调用delete()方法删除指定键值的数据。示例代码如下所示：
    
    public Delete = (() => {
      Logger.info('DeleteData start');
      if (kvStore === undefined) {
        Logger.info('DeleteData: kvStore not initialized');
        return;
      }
      const KEY\_TEST\_STRING\_ELEMENT = 'key\_test\_string';
      try {
        kvStore.delete(KEY\_TEST\_STRING\_ELEMENT, (err) => {
          if (err !== undefined) {
            Logger.error(\`Failed to delete data. Code:${err.code},message:${err.message}\`);
            return;
          }
          Logger.info('Succeeded in deleting data.');
        });
      } catch (e) {
        let error = e as BusinessError;
        Logger.error(\`An unexpected error occurred. Code:${error.code},message:${error.message}\`);
      }
    })
    
7.  调用closeKVStore()方法通过storeId的值关闭指定的分布式键值数据库。示例代码如下所示：
    
    public CloseKVStore = (()=>{
      Logger.info('CloseKVStore start');
      if (kvManager === undefined) {
        Logger.info('KvManager not initialized');
        return;
      }
      try {
        // appId为应用的bundleName
        kvStore = undefined;
        kvManager.closeKVStore(appId, storeId, (err: BusinessError)=> {
          if (err) {
            Logger.error(\`Failed to close KVStore.code is ${err.code},message is ${err.message}\`);
            return;
          }
          Logger.info('Succeeded in closing KVStore');
        });
      } catch (e) {
        let error = e as BusinessError;
        Logger.error(\`An unexpected error occurred. Code:${error.code},message:${error.message}\`);
      }
    })
    
8.  调用deleteKVStore()方法通过storeId的值删除指定的分布式键值数据库。示例代码如下所示：
    
    public DeleteKvStore = (()=>{
      Logger.info('DeleteKvStore start');
      if (kvManager === undefined) {
        Logger.info('KvManager not initialized');
        return;
      }
      try {
        // appId为应用的bundleName
        kvStore = undefined;
        kvManager.deleteKVStore(appId, storeId, (err: BusinessError)=> {
          if (err) {
            Logger.error(\`Failed to delete KVStore.code is ${err.code},message is ${err.message}\`);
            return;
          }
          Logger.info('Succeeded in deleting KVStore');
        });
      } catch (e) {
        let error = e as BusinessError;
        Logger.error(\`An unexpected error occurred. Code:${error.code},message:${error.message}\`);
      }
    })
    

#### 示例代码

*   [实现键值型数据库读写功能](https://gitcode.com/HarmonyOS_Samples/KVStore)