HarmonyOS实战开发:@ohos.data.distributedKVStore (分布式键值数据库)

分布式键值数据库为应用程序提供不同设备间数据库的分布式协同能力。通过调用分布式键值数据库各个接口,应用程序可将数据保存到分布式键值数据库中,并可对分布式键值数据库中的数据进行增加、删除、修改、查询、同步等操作。

该模块提供以下分布式键值数据库相关的常用功能:

  • KVManager:分布式键值数据库管理实例,用于获取数据库的相关信息。
  • KVStoreResultSet:提供获取数据库结果集的相关方法,包括查询和移动数据读取位置等。
  • Query:使用谓词表示数据库查询,提供创建Query实例、查询数据库中的数据和添加谓词的方法。
  • SingleKVStore:单版本分布式键值数据库,不对数据所属设备进行区分,提供查询数据和同步数据的方法。
  • DeviceKVStore:设备协同数据库,继承自SingleKVStore,以设备维度对数据进行区分,提供查询数据和同步数据的方法。

说明:

本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。

导入模块

import distributedKVStore from '@ohos.data.distributedKVStore';复制到剪贴板错误复制

KVManagerConfig

提供KVManager实例的配置信息,包括调用方的包名和应用的上下文。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

名称类型必填说明
contextContext应用的上下文。
FA模型的应用Context定义见Context
Stage模型的应用Context定义见Context
从API version 10开始,context的参数类型为BaseContext
bundle名称字符串调用方的包名。

Constants

分布式键值数据库常量。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

名称说明
MAX_KEY_LENGTH1024数据库中Key允许的最大长度,单位字节。
MAX_VALUE_LENGTH4194303数据库中Value允许的最大长度,单位字节。
MAX_KEY_LENGTH_DEVICE896设备协同数据库中key允许的最大长度,单位字节。
MAX_STORE_ID_LENGTH128数据库标识符允许的最大长度,单位字节。
MAX_QUERY_LENGTH512000最大查询长度,单位字节。
MAX_BATCH_SIZE128最大批处理操作数量。

ValueType

数据类型枚举。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

名称说明
STRING表示值类型为字符串。
INTEGER表示值类型为整数。
FLOAT表示值类型为浮点数。
BYTE_ARRAY表示值类型为字节数组。
BOOLEAN表示值类型为布尔值。
DOUBLE表示值类型为双浮点数。

Value

存储在数据库中的值对象。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

名称类型必填说明
typeValueType值类型。
valueUint8Array | string | number | boolean值。

Entry

存储在数据库中的键值对。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

名称类型必填说明
keystring键值。
valueValue值对象。

ChangeNotification

数据变更时通知的对象,包括数据插入的数据、更新的数据、删除的数据和设备ID。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

名称类型必填说明
insertEntriesEntry[]数据添加记录。
updateEntriesEntry[]数据更新记录。
deleteEntriesEntry[]数据删除记录。
deviceIdstring设备ID,此处为设备UUID。

SyncMode

同步模式枚举。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

名称说明
PULL_ONLY表示只能从远端拉取数据到本端。
PUSH_ONLY表示只能从本端推送数据到远端。
PUSH_PULL表示从本端推送数据到远端,然后从远端拉取数据到本端。

SubscribeType

订阅类型枚举。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

名称说明
SUBSCRIBE_TYPE_LOCAL表示订阅本地数据变更。
SUBSCRIBE_TYPE_REMOTE表示订阅远端数据变更。
SUBSCRIBE_TYPE_ALL表示订阅远端和本地数据变更。

KVStoreType

分布式键值数据库类型枚举。

名称说明
DEVICE_COLLABORATION表示多设备协同数据库。
数据库特点: 数据以设备的维度管理,不存在冲突;支持按照设备的维度查询数据。
系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore
SINGLE_VERSION表示单版本数据库。
数据库特点: 数据不分设备,设备之间修改相同的key会覆盖。
系统能力: SystemCapability.DistributedDataManager.KVStore.Core

SecurityLevel

数据库的安全级别枚举。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

名称说明
S1表示数据库的安全级别为低级别,数据的泄露、篡改、破坏、销毁可能会给个人或组织导致有限的不利影响。
例如,性别、国籍,用户申请记录等。
S2表示数据库的安全级别为中级别,数据的泄露、篡改、破坏、销毁可能会给个人或组织导致严重的不利影响。
例如,个人详细通信地址,姓名昵称等。
S3表示数据库的安全级别为高级别,数据的泄露、篡改、破坏、销毁可能会给个人或组织导致严峻的不利影响。
例如,个人实时精确定位信息、运动轨迹等。
S4表示数据库的安全级别为关键级别,业界法律法规中定义的特殊数据类型,涉及个人的最私密领域的信息或者一旦泄露、篡改、破坏、销毁可能会给个人或组织造成重大的不利影响数据。
例如,政治观点、宗教、和哲学信仰、工会成员资格、基因数据、生物信息、健康和性生活状况、性取向等或设备认证鉴权、个人的信用卡等财务信息。

Options

用于提供创建数据库的配置信息。

名称类型必填说明
createIfMissingboolean当数据库文件不存在时是否创建数据库,默认为true,即创建。
系统能力: SystemCapability.DistributedDataManager.KVStore.Core
encryptboolean设置数据库文件是否加密,默认为false,即不加密。
系统能力: SystemCapability.DistributedDataManager.KVStore.Core
backupboolean设置数据库文件是否备份,默认为true,即备份。
系统能力: SystemCapability.DistributedDataManager.KVStore.Core
autoSyncboolean设置数据库文件是否自动同步。默认为false,即手动同步。
系统能力: SystemCapability.DistributedDataManager.KVStore.Core
需要权限: ohos.permission.DISTRIBUTED_DATASYNC
kvStoreTypeKVStoreType设置要创建的数据库类型,默认为DEVICE_COLLABORATION,即多设备协同数据库。
系统能力: SystemCapability.DistributedDataManager.KVStore.Core
securityLevelSecurityLevel设置数据库安全级别。
系统能力: SystemCapability.DistributedDataManager.KVStore.Core
schemaSchema设置定义存储在数据库中的值,默认为undefined,即不使用Schema。
系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

Schema

表示数据库模式,可以在创建或打开数据库时创建Schema对象并将它们放入Options中。

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

名称类型可读可写说明
rootFieldNode表示json根对象。
indexesArray<string>表示json类型的字符串数组。
modenumber表示Schema的模式。
skipnumberSchema的跳跃大小。

constructor

constructor()

用于创建Schema实例的构造函数。

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

FieldNode

表示 Schema 实例的节点,提供定义存储在数据库中的值的方法。

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

名称类型可读可写说明
nullableboolean表示数据库字段是否可以为空。
defaultstring表示Fieldnode的默认值。
typenumber表示指定节点对应数据类型的值。

constructor

constructor(name: string)

用于创建带有string字段FieldNode实例的构造函数。

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
namestringFieldNode的值。

appendChild

appendChild(child: FieldNode): boolean

在当前 FieldNode 中添加一个子节点。

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
childFieldNode要附加的域节点。

返回值:

类型说明
boolean返回true表示子节点成功添加到FieldNode;返回false则表示操作失败。

示例:


try {
  let node: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("root");
  let child1: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("child1");
  let child2: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("child2");
  let child3: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("child3");
  node.appendChild(child1);
  node.appendChild(child2);
  node.appendChild(child3);
  console.info("appendNode " + JSON.stringify(node));
  child1 = null;
  child2 = null;
  child3 = null;
  node = null;
} catch (e) {
  console.error("AppendChild " + e);
}Copy to clipboardErrorCopied

distributedKVStore.createKVManager

createKVManager(config: KVManagerConfig): KVManager

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

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
configKVManagerConfig提供KVManager实例的配置信息,包括调用方的包名和用户信息。

返回值:

类型说明
KVManager返回创建的KVManager对象实例。

示例:

Stage模型下的示例:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';

let kvManager: distributedKVStore.KVManager;

export default class EntryAbility extends UIAbility {
  onCreate() {
    console.info("MyAbilityStage 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 is ${error.code},message is ${error.message}`);
    }
  }
}Copy to clipboardErrorCopied

FA模型下的示例:

import featureAbility from '@ohos.ability.featureAbility';
import { BusinessError } from '@ohos.base';

let kvManager: distributedKVStore.KVManager;
let context = featureAbility.getContext()
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 is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

KVManager

分布式键值数据库管理实例,用于获取分布式键值数据库的相关信息。在调用KVManager的方法前,需要先通过createKVManager构建一个KVManager实例。

getKVStore

getKVStore<T>(storeId: string, options: Options, callback: AsyncCallback<T>): void

通过指定Options和storeId,创建并获取分布式键值数据库,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
storeIdstring数据库唯一标识符,长度不大于MAX_STORE_ID_LENGTH
optionsOptions创建分布式键值实例的配置信息。
callbackAsyncCallback<T>回调函数。返回创建的分布式键值数据库实例(根据kvStoreType的不同,可以创建SingleKVStore实例和DeviceKVStore实例)。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100002Open existed database with changed options.
15100003Database corrupted.

示例:

import { BusinessError } from '@ohos.base';

let kvStore: distributedKVStore.SingleKVStore | null;
try {
  const options: distributedKVStore.Options = {
    createIfMissing: true,
    encrypt: false,
    backup: false,
    autoSync: true,
    kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
    securityLevel: distributedKVStore.SecurityLevel.S2,
  };
  kvManager.getKVStore('storeId', options, (err, store: distributedKVStore.SingleKVStore) => {
    if (err) {
      console.error(`Failed to get KVStore.code is ${err.code},message is ${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 is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getKVStore

getKVStore<T>(storeId: string, options: Options): Promise<T>

通过指定Options和storeId,创建并获取分布式键值数据库,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
storeIdstring数据库唯一标识符,长度不大于MAX_STORE_ID_LENGTH
optionsOptions创建分布式键值实例的配置信息。

返回值:

类型说明
Promise<T>Promise对象。返回创建的分布式键值数据库实例(根据kvStoreType的不同,可以创建SingleKVStore实例和DeviceKVStore实例。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100002Open existed database with changed options.
15100003Database corrupted.

示例:

import { BusinessError } from '@ohos.base';

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

closeKVStore

closeKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void

通过storeId的值关闭指定的分布式键值数据库,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
appIdstring所调用数据库方的包名。
storeIdstring要关闭的数据库唯一标识符,长度不大于MAX_STORE_ID_LENGTH
callbackAsyncCallback<void>回调函数。

示例:

import { BusinessError } from '@ohos.base';

let kvStore: distributedKVStore.SingleKVStore | null;
const options: distributedKVStore.Options = {
  createIfMissing: true,
  encrypt: false,
  backup: false,
  autoSync: true,
  kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
  schema: undefined,
  securityLevel: distributedKVStore.SecurityLevel.S2,
}
try {
  kvManager.getKVStore('storeId', options, async (err, store: distributedKVStore.SingleKVStore | null) => {
    if (err != undefined) {
      console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in getting KVStore');
    kvStore = store;
    kvStore = null;
    store = null;
    kvManager.closeKVStore('appId', 'storeId', (err)=> {
      if (err != undefined) {
        console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`);
        return;
      }
      console.info('Succeeded in closing KVStore');
    });
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

closeKVStore

closeKVStore(appId: string, storeId: string): Promise<void>

通过storeId的值关闭指定的分布式键值数据库,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
appId字符串所调用数据库方的包名。
storeId字符串要关闭的数据库唯一标识符,长度不大于MAX_STORE_ID_LENGTH

返回值:

类型说明
承诺<无效>无返回结果的Promise对象。

示例:

import { BusinessError } from '@ohos.base';

let kvStore: distributedKVStore.SingleKVStore | null;

const options: distributedKVStore.Options = {
  createIfMissing: true,
  encrypt: false,
  backup: false,
  autoSync: true,
  kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
  schema: undefined,
  securityLevel: distributedKVStore.SecurityLevel.S2,
}
try {
  kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options).then(async (store: distributedKVStore.SingleKVStore | null) => {
    console.info('Succeeded in getting KVStore');
    kvStore = store;
    kvStore = null;
    store = null;
    kvManager.closeKVStore('appId', 'storeId').then(() => {
      console.info('Succeeded in closing KVStore');
    }).catch((err: BusinessError) => {
      console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to close KVStore.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

deleteKVStore

deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void

通过storeId的值删除指定的分布式键值数据库,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
appId字符串所调用数据库方的包名。
storeId字符串要删除的数据库唯一标识符,长度不大于MAX_STORE_ID_LENGTH
回调AsyncCallback<void>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100004Not found.

示例:

import { BusinessError } from '@ohos.base';

let kvStore: distributedKVStore.SingleKVStore | null;

const options: distributedKVStore.Options = {
  createIfMissing: true,
  encrypt: false,
  backup: false,
  autoSync: true,
  kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
  schema: undefined,
  securityLevel: distributedKVStore.SecurityLevel.S2,
}
try {
  kvManager.getKVStore('store', options, async (err, store: distributedKVStore.SingleKVStore | null) => {
    if (err != undefined) {
      console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in getting KVStore');
    kvStore = store;
    kvStore = null;
    store = null;
    kvManager.deleteKVStore('appId', 'storeId', (err) => {
      if (err != undefined) {
        console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`);
        return;
      }
      console.info(`Succeeded in deleting KVStore`);
    });
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to delete KVStore.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

deleteKVStore

deleteKVStore(appId: string, storeId: string): Promise<void>

通过storeId的值删除指定的分布式键值数据库,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
appIdstring所调用数据库方的包名。
storeIdstring要删除的数据库唯一标识符,长度不大于MAX_STORE_ID_LENGTH

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100004Not found.

示例:

import { BusinessError } from '@ohos.base';

let kvStore: distributedKVStore.SingleKVStore | null;

const options: distributedKVStore.Options = {
  createIfMissing: true,
  encrypt: false,
  backup: false,
  autoSync: true,
  kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
  schema: undefined,
  securityLevel: distributedKVStore.SecurityLevel.S2,
}
try {
  kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options).then(async (store: distributedKVStore.SingleKVStore | null) => {
    console.info('Succeeded in getting KVStore');
    kvStore = store;
    kvStore = null;
    store = null;
    kvManager.deleteKVStore('appId', 'storeId').then(() => {
      console.info('Succeeded in deleting KVStore');
    }).catch((err: BusinessError) => {
      console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to delete KVStore.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getAllKVStoreId

getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void

获取所有通过getKVStore方法创建的且没有调用deleteKVStore方法删除的分布式键值数据库的storeId,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
appIdstring所调用数据库方的包名。
callbackAsyncCallback<string[]>回调函数。返回所有创建的分布式键值数据库的storeId。

示例:

import { BusinessError } from '@ohos.base';

try {
  kvManager.getAllKVStoreId('appId', (err, data) => {
    if (err != undefined) {
      console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in getting AllKVStoreId');
    console.info(`GetAllKVStoreId size = ${data.length}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get AllKVStoreId.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getAllKVStoreId

getAllKVStoreId(appId: string): Promise<string[]>

获取所有通过getKVStore方法创建的且没有调用deleteKVStore方法删除的分布式键值数据库的storeId,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
appId字符串所调用数据库方的包名。

返回值:

类型说明
Promise<string[]>Promise对象。返回所有创建的分布式键值数据库的storeId。

示例:

import { BusinessError } from '@ohos.base';

try {
  console.info('GetAllKVStoreId');
  kvManager.getAllKVStoreId('appId').then((data: string[]) => {
    console.info('Succeeded in getting AllKVStoreId');
    console.info(`GetAllKVStoreId size = ${data.length}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get AllKVStoreId.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

on('distributedDataServiceDie')

on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void

订阅服务状态变更通知。如果服务终止,需要重新注册数据变更通知和同步完成事件回调通知,并且同步操作会返回失败。

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
事件字符串订阅的事件名,固定为'distributedDataServiceDie',即服务状态变更事件。
deathCallbackCallback<void>回调函数。

示例:

import { BusinessError } from '@ohos.base';

try {
  console.info('KVManagerOn');
  const deathCallback = () => {
    console.info('death callback call');
  }
  kvManager.on('distributedDataServiceDie', deathCallback);
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

off('distributedDataServiceDie')

off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void

取消订阅服务状态变更通知。参数中的deathCallback必须是已经订阅过的deathCallback,否则会取消订阅失败。

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
事件字符串取消订阅的事件名,固定为'distributedDataServiceDie',即服务状态变更事件。
deathCallbackCallback<void>回调函数。如果该参数不填,那么会将之前订阅过的所有的deathCallback取消订阅。

示例:

import { BusinessError } from '@ohos.base';

try {
  console.info('KVManagerOff');
  const deathCallback = () => {
    console.info('death callback call');
  }
  kvManager.off('distributedDataServiceDie', deathCallback);
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

KVStoreResultSet

提供获取数据库结果集的相关方法,包括查询和移动数据读取位置等。同时允许打开的结果集的最大数量为8个。

在调用KVStoreResultSet的方法前,需要先通过getKVStore构建一个SingleKVStore或者DeviceKVStore实例。

getCount

getCount(): number

获取结果集中的总行数。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
返回数据的总行数。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let count: number;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('getResultSet succeed.');
    resultSet = result;
    count = resultSet.getCount();
    console.info("getCount succeed:" + count);
  }).catch((err: BusinessError) => {
    console.error('getResultSet failed: ' + err);
  });
} catch (e) {
  console.error("getCount failed: " + e);
}Copy to clipboardErrorCopied

getPosition

getPosition(): number

获取结果集中当前的读取位置。读取位置会因moveToFirstmoveToLast等操作而发生变化。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
返回当前读取位置。取值范围>= -1,值为 -1 时表示还未开始读取,值为 0 时表示第一行。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let position: number;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('getResultSet succeeded.');
    resultSet = result;
    position = resultSet.getPosition();
    console.info("getPosition succeed:" + position);
  }).catch((err: BusinessError) => {
    console.error('getResultSet failed: ' + err);
  });
} catch (e) {
  console.error("getPosition failed: " + e);
}Copy to clipboardErrorCopied

moveToFirst

moveToFirst(): boolean

将读取位置移动到第一行。如果结果集为空,则返回false。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
boolean返回true表示操作成功;返回false则表示操作失败。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let moved: boolean;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('getResultSet succeed.');
    resultSet = result;
    moved = resultSet.moveToFirst();
    console.info("moveToFirst succeed: " + moved);
  }).catch((err: BusinessError) => {
    console.error('getResultSet failed: ' + err);
  });
} catch (e) {
  console.error("moveToFirst failed " + e);
}Copy to clipboardErrorCopied

moveToLast

moveToLast(): boolean

将读取位置移动到最后一行。如果结果集为空,则返回false。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
boolean返回true表示操作成功;返回false则表示操作失败。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let moved: boolean;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('getResultSet succeed.');
    resultSet = result;
    moved = resultSet.moveToLast();
    console.info("moveToLast succeed:" + moved);
  }).catch((err: BusinessError) => {
    console.error('getResultSet failed: ' + err);
  });
} catch (e) {
  console.error("moveToLast failed: " + e);
}Copy to clipboardErrorCopied

moveToNext

moveToNext(): boolean

将读取位置移动到下一行。如果结果集为空,则返回false。适用于全量获取数据库结果集的场景。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
boolean返回true表示操作成功;返回false则表示操作失败。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let moved: boolean;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('getResultSet succeed.');
    resultSet = result;
    do {
      moved = resultSet.moveToNext();
      console.info("moveToNext succeed: " + moved);
    } while (moved)
  }).catch((err: BusinessError) => {
    console.error('getResultSet failed: ' + err);
  });
} catch (e) {
  console.error("moveToNext failed: " + e);
}Copy to clipboardErrorCopied

moveToPrevious

moveToPrevious(): boolean

将读取位置移动到上一行。如果结果集为空,则返回false。适用于全量获取数据库结果集的场景。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
boolean返回true表示操作成功;返回false则表示操作失败。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let moved: boolean;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('getResultSet succeed.');
    resultSet = result;
    moved = resultSet.moveToLast();
    moved = resultSet.moveToPrevious();
    console.info("moveToPrevious succeed:" + moved);
  }).catch((err: BusinessError) => {
    console.error('getResultSet failed: ' + err);
  });
} catch (e) {
  console.error("moveToPrevious failed: " + e);
}Copy to clipboardErrorCopied

move

move(offset: number): boolean

将读取位置移动到当前位置的相对偏移量。即当前游标位置向下偏移 offset 行。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
offsetnumber表示与当前位置的相对偏移量,负偏移表示向后移动,正偏移表示向前移动。

返回值:

类型说明
boolean返回true表示操作成功;返回false则表示操作失败。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let moved: boolean;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('Succeeded in getting resultSet');
    resultSet = result;
    moved = resultSet.move(2); //若当前位置为0,将读取位置从绝对位置为0的位置移动2行,即移动到绝对位置为2,行数为3的位置
    console.info(`Succeeded in moving.moved = ${moved}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to move.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

moveToPosition

moveToPosition(position: number): boolean

将读取位置从 0 移动到绝对位置。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
positionnumber表示绝对位置。

返回值:

类型说明
boolean返回true表示操作成功;返回false则表示操作失败。

示例

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let moved: boolean;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('Succeeded in getting resultSet');
    resultSet = result;
    moved = resultSet.moveToPosition(1);
    console.info(`Succeeded in moving to position.moved=${moved}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to move to position.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

isFirst

isFirst(): boolean

检查读取位置是否为第一行。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
boolean返回true表示读取位置为第一行;返回false表示读取位置不是第一行。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let isfirst: boolean;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('getResultSet succeed.');
    resultSet = result;
    isfirst = resultSet.isFirst();
    console.info("Check isFirst succeed:" + isfirst);
  }).catch((err: BusinessError) => {
    console.error('getResultSet failed: ' + err);
  });
} catch (e) {
  console.error("Check isFirst failed: " + e);
}Copy to clipboardErrorCopied

isLast

isLast(): boolean

检查读取位置是否为最后一行。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
boolean返回true表示读取位置为最后一行;返回false表示读取位置不是最后一行。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let islast: boolean;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('getResultSet succeed.');
    resultSet = result;
    islast = resultSet.isLast();
    console.info("Check isLast succeed: " + islast);
  }).catch((err: BusinessError) => {
    console.error('getResultSet failed: ' + err);
  });
} catch (e) {
  console.error("Check isLast failed: " + e);
}Copy to clipboardErrorCopied

isBeforeFirst

isBeforeFirst(): boolean

检查读取位置是否在第一行之前。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
boolean返回true表示读取位置在第一行之前;返回false表示读取位置不在第一行之前。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('getResultSet succeed.');
    resultSet = result;
    let isbeforefirst = resultSet.isBeforeFirst();
    console.info("Check isBeforeFirst succeed: " + isbeforefirst);
  }).catch((err: BusinessError) => {
    console.error('getResultSet failed: ' + err);
  });
} catch (e) {
  console.error("Check isBeforeFirst failed: " + e);
}Copy to clipboardErrorCopied

isAfterLast

isAfterLast(): boolean

检查读取位置是否在最后一行之后。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
boolean返回true表示读取位置在最后一行之后;返回false表示读取位置不在最后一行之后。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('getResultSet succeed.');
    resultSet = result;
    let isafterlast = resultSet.isAfterLast();
    console.info("Check isAfterLast succeed:" + isafterlast);
  }).catch((err: BusinessError) => {
    console.error('getResultSet failed: ' + err);
  });
} catch (e) {
  console.error("Check isAfterLast failed: " + e);
}Copy to clipboardErrorCopied

getEntry

getEntry(): Entry

从当前位置获取对应的键值对。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
Entry返回键值对。

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('getResultSet succeed.');
    resultSet = result;
    let entry = resultSet.getEntry();
    console.info("getEntry succeed:" + JSON.stringify(entry));
  }).catch((err: BusinessError) => {
    console.error('getResultSet failed: ' + err);
  });
} catch (e) {
  console.error("getEntry failed: " + e);
}Copy to clipboardErrorCopied

Query

使用谓词表示数据库查询,提供创建Query实例、查询数据库中的数据和添加谓词的方法。一个Query对象中谓词数量上限为256个。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

constructor

constructor()

用于创建Schema实例的构造函数。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

reset

reset(): Query

重置Query对象。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
Query返回重置的Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
  let query: distributedKVStore.Query | null = new distributedKVStore.Query();
  query.equalTo("key", "value");
  console.info("query is " + query.getSqlLike());
  query.reset();
  console.info("query is " + query.getSqlLike());
  query = null;
} catch (e) {
  console.error("simply calls should be ok :" + e);
}Copy to clipboardErrorCopied

equalTo

equalTo(field: string, value: number|string|boolean): Query

构造一个Query对象来查询具有指定字段的条目,其值等于指定的值。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieIdstring表示指定字段,不能包含' ^ '。
valuenumber|string|boolean表示指定的值。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
  let query: distributedKVStore.Query | null = new distributedKVStore.Query();
  query.equalTo("field", "value");
  console.info(`query is ${query.getSqlLike()}`);
  query = null;
} catch (e) {
  let error = e as BusinessError;
  console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

notEqualTo

notEqualTo(field: string, value: number|string|boolean): Query

构造一个Query对象以查询具有指定字段且值不等于指定值的条目。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieId字符串表示指定字段,不能包含' ^ '。
价值number|string|boolean表示指定的值。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
  let query: distributedKVStore.Query | null = new distributedKVStore.Query();
  query.notEqualTo("field", "value");
  console.info(`query is ${query.getSqlLike()}`);
  query = null;
} catch (e) {
  let error = e as BusinessError;
  console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

greaterThan

greaterThan(field: string, value: number|string|boolean): Query

构造一个Query对象以查询具有大于指定值的指定字段的条目。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数: | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----------------------- | | fieId | string | 是 |表示指定字段,不能包含' ^ '。 | | value | number|string|boolean | 是 | 表示指定的值。|

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.greaterThan("field", "value");
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

lessThan

lessThan(field: string, value: number|string): Query

构造一个Query对象以查询具有小于指定值的指定字段的条目。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieIdstring表示指定字段,不能包含' ^ '。
valuenumber|string表示指定的值。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.lessThan("field", "value");
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

greaterThanOrEqualTo

greaterThanOrEqualTo(field: string, value: number|string): Query

构造一个Query对象以查询具有指定字段且值大于或等于指定值的条目。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieIdstring表示指定字段,不能包含' ^ '。
valuenumber|string表示指定的值。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.greaterThanOrEqualTo("field", "value");
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

lessThanOrEqualTo

lessThanOrEqualTo(field: string, value: number|string): Query

构造一个Query对象以查询具有指定字段且值小于或等于指定值的条目。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieIdstring表示指定字段,不能包含' ^ '。
valuenumber|string表示指定的值。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.lessThanOrEqualTo("field", "value");
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

isNull

isNull(field: string): Query

构造一个Query对象以查询具有值为null的指定字段的条目。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieIdstring表示指定字段,不能包含' ^ '。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.isNull("field");
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

inNumber

inNumber(field: string, valueList: number[]): Query

构造一个Query对象以查询具有指定字段的条目,其值在指定的值列表中。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieId字符串表示指定字段,不能包含' ^ '。
valueListnumber[]表示指定的值列表。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.inNumber("field", [0, 1]);
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

inString

inString(field: string, valueList: string[]): Query

构造一个Query对象以查询具有指定字段的条目,其值在指定的字符串值列表中。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieId字符串表示指定字段,不能包含' ^ '。
valueListstring[]表示指定的字符串值列表。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.inString("field", ['test1', 'test2']);
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

notInNumber

notInNumber(field: string, valueList: number[]): Query

构造一个Query对象以查询具有指定字段的条目,该字段的值不在指定的值列表中。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieId字符串表示指定字段,不能包含' ^ '。
valueListnumber[]表示指定的值列表。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.notInNumber("field", [0, 1]);
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

notInString

notInString(field: string, valueList: string[]): Query

构造一个Query对象以查询具有指定字段且值不在指定字符串值列表中的条目。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieIdstring表示指定字段,不能包含' ^ '。
valueListstring[]表示指定的字符串值列表。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.notInString("field", ['test1', 'test2']);
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

like

like(field: string, value: string): Query

构造一个Query对象以查询具有与指定字符串值相似的指定字段的条目。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieIdstring表示指定字段,不能包含' ^ '。
valuestring表示指定的字符串值。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.like("field", "value");
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

unlike

unlike(field: string, value: string): Query

构造一个Query对象以查询具有与指定字符串值不相似的指定字段的条目。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieIdstring表示指定字段,不能包含' ^ '。
valuestring表示指定的字符串值。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.unlike("field", "value");
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

and

and(): Query

构造一个带有与条件的查询对象。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
Query返回查询对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.notEqualTo("field", "value1");
    query.and();
    query.notEqualTo("field", "value2");
    console.info("query is " + query.getSqlLike());
    query = null;
} catch (e) {
    console.error("duplicated calls should be ok :" + e);
}Copy to clipboardErrorCopied

or

or(): Query

构造一个带有或条件的Query对象。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
Query返回查询对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.notEqualTo("field", "value1");
    query.or();
    query.notEqualTo("field", "value2");
    console.info("query is " + query.getSqlLike());
    query = null;
} catch (e) {
    console.error("duplicated calls should be ok :" + e);
}Copy to clipboardErrorCopied

orderByAsc

orderByAsc(field: string): Query

构造一个Query对象,将查询结果按升序排序。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieIdstring表示指定字段,不能包含' ^ '。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.notEqualTo("field", "value");
    query.orderByAsc("field");
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

orderByDesc

orderByDesc(field: string): Query

构造一个Query对象,将查询结果按降序排序。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieIdstring表示指定字段,不能包含' ^ '。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.notEqualTo("field", "value");
    query.orderByDesc("field");
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

limit

limit(total: number, offset: number): Query

构造一个Query对象来指定结果的数量和开始位置。该接口必须要在Query对象查询和升降序等操作之后调用,调用limit接口后,不可再对Query对象进行查询和升降序等操作。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
totalnumber表示指定的结果数。
offsetnumber表示起始位置。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

let total = 10;
let offset = 1;
try {
  let query: distributedKVStore.Query | null = new distributedKVStore.Query();
  query.notEqualTo("field", "value");
  query.limit(total, offset);
  console.info(`query is ${query.getSqlLike()}`);
  query = null;
} catch (e) {
  let error = e as BusinessError;
  console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

isNotNull

isNotNull(field: string): Query

构造一个Query对象以查询具有值不为null的指定字段的条目。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
fieIdstring表示指定字段,不能包含' ^ '。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
  let query: distributedKVStore.Query | null = new distributedKVStore.Query();
  query.isNotNull("field");
  console.info(`query is ${query.getSqlLike()}`);
  query = null;
} catch (e) {
  let error = e as BusinessError;
  console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

beginGroup

beginGroup(): Query

创建一个带有左括号的查询条件组。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.beginGroup();
    query.isNotNull("field");
    query.endGroup();
    console.info("query is " + query.getSqlLike());
    query = null;
} catch (e) {
    console.error("duplicated calls should be ok :" + e);
}Copy to clipboardErrorCopied

endGroup

endGroup(): Query

创建一个带有右括号的查询条件组。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.beginGroup();
    query.isNotNull("field");
    query.endGroup();
    console.info("query is " + query.getSqlLike());
    query = null;
} catch (e) {
    console.error("duplicated calls should be ok :" + e);
}Copy to clipboardErrorCopied

prefixKey

prefixKey(prefix: string): Query

创建具有指定键前缀的查询条件。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
prefixstring表示指定的键前缀。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.prefixKey("$.name");
    query.prefixKey("0");
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

setSuggestIndex

setSuggestIndex(index: string): Query

设置一个指定的索引,将优先用于查询。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
indexstring指示要设置的索引。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.setSuggestIndex("$.name");
    query.setSuggestIndex("0");
    console.info(`query is ${query.getSqlLike()}`);
    query = null;
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

deviceId

deviceId(deviceId:string):Query

添加设备ID作为key的前缀。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
deviceId字符串指示查询的设备ID。

返回值:

类型说明
Query返回Query对象。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    query.deviceId("deviceId");
    console.info(`query is ${query.getSqlLike()}`);
} catch (e) {
    let error = e as BusinessError;
    console.error(`duplicated calls should be ok.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

getSqlLike

getSqlLike():string

获取Query对象的查询语句。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
字符串返回一个字段列中包含对应子串的结果。

示例:

import { BusinessError } from '@ohos.base';

try {
    let query: distributedKVStore.Query | null = new distributedKVStore.Query();
    let sql1 = query.getSqlLike();
    console.info(`GetSqlLike sql= ${sql1}`);
} catch (e) {
    console.error("duplicated calls should be ok : " + e);
}复制到剪贴板错误复制

SingleKVStore

SingleKVStore数据库实例,提供增加数据、删除数据和订阅数据变更、订阅数据同步完成的方法。

在调用SingleKVStore的方法前,需要先通过getKVStore构建一个SingleKVStore实例。

put

put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void

添加指定类型键值对到数据库,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keystring要添加数据的key,不能为空且长度不大于MAX_KEY_LENGTH
valueUint8Array | string | number | boolean要添加数据的value,支持Uint8Array、number 、 string 、boolean,Uint8Array、string 的长度不大于MAX_VALUE_LENGTH
callbackAsyncCallback<void>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
    if (err != undefined) {
      console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info("Succeeded in putting");
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

put

put(key: string, value: Uint8Array | string | number | boolean): Promise<void>

添加指定类型键值对到数据库,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keystring要添加数据的key,不能为空且长度不大于MAX_KEY_LENGTH
valueUint8Array | string | number | boolean要添加数据的value,支持Uint8Array、number 、 string 、boolean,Uint8Array、string 的长度不大于MAX_VALUE_LENGTH

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => {
    console.info(`Succeeded in putting data`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

putBatch

putBatch(entries: Entry[], callback: AsyncCallback<void>): void

批量插入键值对到SingleKVStore数据库中,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
entriesEntry[]表示要批量插入的键值对。一个entries对象中允许的最大条目个数为128个。
callbackAsyncCallback<void>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  console.info(`entries: ${entries}`);
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting Batch');
    if (kvStore != null) {
      kvStore.getEntries('batch_test_string_key', (err, entries) => {
        if (err != undefined) {
          console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
        }
        console.info('Succeeded in getting Entries');
        console.info(`entries.length: ${entries.length}`);
        console.info(`entries[0]: ${entries[0]}`);
      });
    } else {
      console.error('KvStore is null'); //后续示例代码与此处保持一致
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `);
}Copy to clipboardErrorCopied

putBatch

putBatch(entries: Entry[]): Promise<void>

批量插入键值对到SingleKVStore数据库中,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
entriesEntry[]表示要批量插入的键值对。一个entries对象中允许的最大条目个数为128个。

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  console.info(`entries: ${entries}`);
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting Batch');
    if (kvStore != null) {
      kvStore.getEntries('batch_test_string_key').then((entries) => {
        console.info('Succeeded in getting Entries');
        console.info(`PutBatch ${entries}`);
      }).catch((err: BusinessError) => {
        console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `);
}复制到剪贴板错误复制

putBatch

putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void

将值写入SingleKVStore数据库,使用callback异步回调。

模型约束: 此接口仅可在Stage模型下使用

系统接口: 此接口为系统接口。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
价值Array<ValuesBucket>表示要插入的数据。
回调AsyncCallback<void>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

try {
  let v8Arr: distributedKVStore.Entry[] = [];
  let arr = new Uint8Array([4, 5, 6, 7]);
  let vb1: distributedKVStore.Entry = { key: "name_1", value: 32 }
  let vb2: distributedKVStore.Entry = { key: "name_2", value: arr };
  let vb3: distributedKVStore.Entry = { key: "name_3", value: "lisi" };

  v8Arr.push(vb1);
  v8Arr.push(vb2);
  v8Arr.push(vb3);
  kvStore.putBatch(v8Arr, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting batch');
  })
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to put batch.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

putBatch

putBatch(value: Array<ValuesBucket>): Promise<void>

将valuesbucket类型的值写入SingleKVStore数据库,使用Promise异步回调。

模型约束: 此接口仅可在Stage模型下使用

系统接口: 此接口为系统接口。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
valueArray<ValuesBucket>表示要插入的数据。

返回值:

类型说明
Promise<void>五返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

try {
  let v8Arr: distributedKVStore.Entry[] = [];
  let arr = new Uint8Array([4, 5, 6, 7]);
  let vb1: distributedKVStore.Entry = { key: "name_1", value: 32 }
  let vb2: distributedKVStore.Entry = { key: "name_2", value: arr };
  let vb3: distributedKVStore.Entry = { key: "name_3", value: "lisi" };

  v8Arr.push(vb1);
  v8Arr.push(vb2);
  v8Arr.push(vb3);
  kvStore.putBatch(v8Arr).then(async () => {
    console.info(`Succeeded in putting patch`);
  }).catch((err: BusinessError) => {
    console.error(`putBatch fail.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`putBatch fail.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

delete

delete(key: string, callback: AsyncCallback<void>): void

从数据库中删除指定键值的数据,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keystring要删除数据的key,不能为空且长度不大于MAX_KEY_LENGTH
callbackAsyncCallback<void>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
    if (err != undefined) {
      console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting');
    if (kvStore != null) {
      kvStore.delete(KEY_TEST_STRING_ELEMENT, (err) => {
        if (err != undefined) {
          console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in deleting');
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

delete

delete(key: string): Promise<void>

从数据库中删除指定键值的数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keystring要删除数据的key,不能为空且长度不大于MAX_KEY_LENGTH

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => {
    console.info(`Succeeded in putting data`);
    if (kvStore != null) {
      kvStore.delete(KEY_TEST_STRING_ELEMENT).then(() => {
        console.info('Succeeded in deleting');
      }).catch((err: BusinessError) => {
        console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

delete

delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>)

从数据库中删除符合predicates条件的键值对,使用callback异步回调。

模型约束: 此接口仅可在Stage模型下使用

系统接口: 此接口为系统接口。

系统能力: SystemCapability.DistributedDataManager.DataShare.Provider

参数:

参数名类型必填说明
predicatesdataSharePredicates.DataSharePredicates指示筛选条件,当此参数为null时,应定义处理逻辑。
callbackAsyncCallback<void>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

try {
  let predicates = new dataSharePredicates.DataSharePredicates();
  let arr = ["name"];
  predicates.inKeys(arr);
  kvStore.put("name", "bob", (err) => {
    if (err != undefined) {
      console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info("Succeeded in putting");
    if (kvStore != null) {
      kvStore.delete(predicates, (err) => {
        if (err == undefined) {
          console.info('Succeeded in deleting');
        } else {
          console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
        }
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

delete

delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void>

从数据库中删除符合predicates条件的键值对,使用Promise异步回调。

模型约束: 此接口仅可在Stage模型下使用

系统接口: 此接口为系统接口。

系统能力: SystemCapability.DistributedDataManager.DataShare.Provider

参数:

参数名类型必填说明
predicatesdataSharePredicates.DataSharePredicates指示筛选条件,当此参数为null时,应定义处理逻辑。

返回值:

类型说明
承诺<无效>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

try {
  let predicates = new dataSharePredicates.DataSharePredicates();
  let arr = ["name"];
  predicates.inKeys(arr);
  kvStore.put("name", "bob").then(() => {
    console.info(`Succeeded in putting data`);
    if (kvStore != null) {
      kvStore.delete(predicates).then(() => {
        console.info('Succeeded in deleting');
      }).catch((err: BusinessError) => {
        console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

deleteBatch

deleteBatch(keys: string[], callback: AsyncCallback<void>): void

批量删除SingleKVStore数据库中的键值对,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keysstring[]表示要批量删除的键值对。
callbackAsyncCallback<void>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  let keys: string[] = [];
  for (let i = 0; i < 5; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
    keys.push(key + i);
  }
  console.info(`entries: ${entries}`);
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting Batch');
    if (kvStore != null) {
      kvStore.deleteBatch(keys, async (err) => {
        if (err != undefined) {
          console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in deleting Batch');
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

deleteBatch

deleteBatch(keys: string[]): Promise<void>

批量删除SingleKVStore数据库中的键值对,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keysstring[]表示要批量删除的键值对。

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  let keys: string[] = [];
  for (let i = 0; i < 5; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
    keys.push(key + i);
  }
  console.info(`entries: ${entries}`);
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting Batch');
    if (kvStore != null) {
      kvStore.deleteBatch(keys).then(() => {
        console.info('Succeeded in deleting Batch');
      }).catch((err: BusinessError) => {
        console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

removeDeviceData

removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void

删除指定设备的数据,使用callback异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceId字符串表示要删除设备的名称。
回调AsyncCallback<void>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async (err) => {
    console.info('Succeeded in putting data');
    const deviceid = 'no_exist_device_id';
    if (kvStore != null) {
      kvStore.removeDeviceData(deviceid, async (err) => {
        if (err == undefined) {
          console.info('succeeded in removing device data');
        } else {
          console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `);
          if (kvStore != null) {
            kvStore.get(KEY_TEST_STRING_ELEMENT, async (err, data) => {
              console.info('Succeeded in getting data');
            });
          }
        }
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`)
}复制到剪贴板错误复制

removeDeviceData

removeDeviceData(deviceId: string): Promise<void>

删除指定设备的数据,使用Promise异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceId字符串表示要删除设备的名称。

返回值:

类型说明
承诺<无效>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
const VALUE_TEST_STRING_ELEMENT = 'value-string-001';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => {
    console.info('Succeeded in putting data');
  }).catch((err: BusinessError) => {
    console.error(`Failed to put data.code is ${err.code},message is ${err.message} `);
  });
  const deviceid = 'no_exist_device_id';
  kvStore.removeDeviceData(deviceid).then(() => {
    console.info('succeeded in removing device data');
  }).catch((err: BusinessError) => {
    console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `);
  });
  kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
    console.info('Succeeded in getting data');
  }).catch((err: BusinessError) => {
    console.error(`Failed to get data.code is ${err.code},message is ${err.message} `);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`)
}复制到剪贴板错误复制

get

get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void

获取指定键的值,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keystring要查询数据的key,不能为空且长度不大于MAX_KEY_LENGTH
callbackAsyncCallback<boolean | string | number | Uint8Array>回调函数。返回获取查询的值。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100004Not found.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';


const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
    if (err != undefined) {
      console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info("Succeeded in putting");
    if (kvStore != null) {
      kvStore.get(KEY_TEST_STRING_ELEMENT, (err, data) => {
        if (err != undefined) {
          console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info(`Succeeded in getting data.data=${data}`);
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

get

get(key: string): Promise<boolean | string | number | Uint8Array>

获取指定键的值,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keystring要查询数据的key,不能为空且长度不大于MAX_KEY_LENGTH

返回值:

类型说明
Promise<Uint8Array | string | boolean | number>Promise对象。返回获取查询的值。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100004Not found.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';


const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => {
    console.info(`Succeeded in putting data`);
    if (kvStore != null) {
      kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
        console.info(`Succeeded in getting data.data=${data}`);
      }).catch((err: BusinessError) => {
        console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getEntries

getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void

获取匹配指定键前缀的所有键值对,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keyPrefixstring表示要匹配的键前缀。
callbackAsyncCallback<Entry[]>回调函数。返回匹配指定前缀的键值对列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  console.info(`entries: ${entries}`);
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting Batch');
    if (kvStore != null) {
      kvStore.getEntries('batch_test_string_key', (err, entries) => {
        if (err != undefined) {
          console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting Entries');
        console.info(`entries.length: ${entries.length}`);
        console.info(`entries[0]: ${entries[0]}`);
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `);
}Copy to clipboardErrorCopied

getEntries

getEntries(keyPrefix: string): Promise<Entry[]>

获取匹配指定键前缀的所有键值对,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keyPrefixstring表示要匹配的键前缀。

返回值:

类型说明
Promise<Entry[]>Promise对象。返回匹配指定前缀的键值对列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';


try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  console.info(`entries: ${entries}`);
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting Batch');
    if (kvStore != null) {
      kvStore.getEntries('batch_test_string_key').then((entries) => {
        console.info('Succeeded in getting Entries');
        console.info(`PutBatch ${entries}`);
      }).catch((err: BusinessError) => {
        console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `);
}Copy to clipboardErrorCopied

getEntries

getEntries(query: Query, callback: AsyncCallback<Entry[]>): void

获取与指定Query对象匹配的键值对列表,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示要匹配的键前缀。
callbackAsyncCallback<Entry[]>回调函数。返回与指定Query对象匹配的键值对列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let arr = new Uint8Array([21, 31]);
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_bool_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.BYTE_ARRAY,
        value: arr
      }
    }
    entries.push(entry);
  }
  console.info(`entries: {entries}`);
  kvStore.putBatch(entries, async (err) => {
    console.info('Succeeded in putting Batch');
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getEntries(query, (err, entries) => {
        if (err != undefined) {
          console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting Entries');
        console.info(`entries.length: ${entries.length}`);
        console.info(`entries[0]: ${entries[0]}`);
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get Entries.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getEntries

getEntries(query: Query): Promise<Entry[]>

获取与指定Query对象匹配的键值对列表,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示查询对象。

返回值:

类型说明
Promise<Entry[]>Promise对象。返回与指定Query对象匹配的键值对列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let arr = new Uint8Array([21, 31]);
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_bool_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.BYTE_ARRAY,
        value: arr
      }
    }
    entries.push(entry);
  }
  console.info(`entries: {entries}`);
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting Batch');
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getEntries(query).then((entries) => {
        console.info('Succeeded in getting Entries');
      }).catch((err: BusinessError) => {
        console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`)
  });
  console.info('Succeeded in getting Entries');
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get Entries.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void

从SingleKVStore数据库中获取具有指定前缀的结果集,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keyPrefixstring表示要匹配的键前缀。
callbackAsyncCallback<KVStoreResultSet>回调函数。返回具有指定前缀的结果集。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting batch');
    if (kvStore != null) {
      kvStore.getResultSet('batch_test_string_key', async (err, result) => {
        if (err != undefined) {
          console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting result set');
        resultSet = result;
        if (kvStore != null) {
          kvStore.closeResultSet(resultSet, (err) => {
            if (err != undefined) {
              console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
              return;
            }
            console.info('Succeeded in closing result set');
          });
        }
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(keyPrefix: string): Promise<KVStoreResultSet>

从SingleKVStore数据库中获取具有指定前缀的结果集,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keyPrefixstring表示要匹配的键前缀。

返回值:

类型说明
Promise<KVStoreResultSet>Promise对象。返回具有指定前缀的结果集。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting batch');
  }).catch((err: BusinessError) => {
    console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
  });
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('Succeeded in getting result set');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet).then(() => {
        console.info('Succeeded in closing result set');
      }).catch((err: BusinessError) => {
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(query: Query, callback: AsyncCallback<KVStoreResultSet>): void

获取与指定Query对象匹配的KVStoreResultSet对象,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示查询对象。
callbackAsyncCallback<KVStoreResultSet>回调函数,获取与指定Query对象匹配的KVStoreResultSet对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting batch');
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getResultSet(query, async (err, result) => {
        if (err != undefined) {
          console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting result set');
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(query: Query): Promise<KVStoreResultSet>

获取与指定Query对象匹配的KVStoreResultSet对象,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示查询对象。

返回值:

类型说明
Promise<KVStoreResultSet>Promise对象。获取与指定Query对象匹配的KVStoreResultSet对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting batch');
  }).catch((err: BusinessError) => {
    console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
  });
  const query = new distributedKVStore.Query();
  query.prefixKey("batch_test");
  kvStore.getResultSet(query).then((result) => {
    console.info('Succeeded in getting result set');
    resultSet = result;
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void

获取与指定Predicate对象匹配的KVStoreResultSet对象,使用callback异步回调。

模型约束: 此接口仅可在Stage模型下使用

系统接口: 此接口为系统接口。

系统能力: SystemCapability.DistributedDataManager.DataShare.Provider

参数:

参数名类型必填说明
predicatesdataSharePredicates.DataSharePredicates指示筛选条件,当此参数为null时,应定义处理逻辑。
callbackAsyncCallback<KVStoreResultSet>回调函数,获取与指定Predicates对象匹配的KVStoreResultSet对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let predicates = new dataSharePredicates.DataSharePredicates();
  predicates.prefixKey("batch_test_string_key");
  kvStore.getResultSet(predicates, async (err, result) => {
    if (err != undefined) {
      console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in getting result set');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet, (err) => {
        if (err != undefined) {
          console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in closing result set');
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet>

获取与指定Predicate对象匹配的KVStoreResultSet对象,使用Promise异步回调。

模型约束: 此接口仅可在Stage模型下使用

系统接口: 此接口为系统接口。

系统能力: SystemCapability.DistributedDataManager.DataShare.Provider

参数:

参数名类型必填说明
predicatesdataSharePredicates.DataSharePredicates指示筛选条件,当此参数为null时,应定义处理逻辑。

返回值:

类型说明
Promise<KVStoreResultSet>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let predicates = new dataSharePredicates.DataSharePredicates();
  predicates.prefixKey("batch_test_string_key");
  kvStore.getResultSet(predicates).then((result) => {
    console.info('Succeeded in getting result set');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet).then(() => {
        console.info('Succeeded in closing result set');
      }).catch((err: BusinessError) => {
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
  });

} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

closeResultSet

closeResultSet(resultSet: KVStoreResultSet, callback: AsyncCallback<void>): void

关闭由SingleKvStore.getResultSet返回的KVStoreResultSet对象,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
resultSetKVStoreResultSet表示要关闭的KVStoreResultSet对象。
callbackAsyncCallback<void>回调函数。

示例:

import { BusinessError } from '@ohos.base';

let resultSet: distributedKVStore.KVStoreResultSet;
try {
  kvStore.getResultSet('batch_test_string_key', async (err, result) => {
    if (err != undefined) {
      console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in getting result set');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet, (err) => {
        if (err != undefined) {
          console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in closing result set');
      })
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}
Copy to clipboardErrorCopied

closeResultSet

closeResultSet(resultSet: KVStoreResultSet): Promise<void>

关闭由SingleKvStore.getResultSet返回的KVStoreResultSet对象,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
resultSetKVStoreResultSet表示要关闭的KVStoreResultSet对象。

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

示例:

import { BusinessError } from '@ohos.base';

let resultSet: distributedKVStore.KVStoreResultSet;
try {
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('Succeeded in getting result set');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet).then(() => {
        console.info('Succeeded in closing result set');
      }).catch((err: BusinessError) => {
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
  });

} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

getResultSize

getResultSize(query: Query, callback: AsyncCallback<number>): void

获取与指定Query对象匹配的结果数,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示查询对象。
callbackAsyncCallback<number>回调函数。返回与指定Query对象匹配的结果数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries, async (err) => {
    console.info('Succeeded in putting batch');
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getResultSize(query, async (err, resultSize) => {
        if (err != undefined) {
          console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting result set size');
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

getResultSize

getResultSize(query: Query): Promise<number>

获取与指定Query对象匹配的结果数,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示查询对象。

返回值:

类型说明
Promise<number>Promise对象。获取与指定QuerV9对象匹配的结果数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting batch');
  }).catch((err: BusinessError) => {
    console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
  });
  const query = new distributedKVStore.Query();
  query.prefixKey("batch_test");
  kvStore.getResultSize(query).then((resultSize) => {
    console.info('Succeeded in getting result set size');
  }).catch((err: BusinessError) => {
    console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}复制到剪贴板错误复制

backup

backup(file:string, callback: AsyncCallback<void>):void

以指定名称备份数据库,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
file字符串备份数据库的指定名称,不能为空且长度不大于MAX_KEY_LENGTH
回调AsyncCallback<void>回调函数。当以指定名称备份数据库成功,err为undefined,否则为错误对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

let file = "BK001";
try {
  kvStore.backup(file, (err) => {
    if (err) {
      console.error(`Failed to backup.code is ${err.code},message is ${err.message} `);
    } else {
      console.info(`Succeeded in backupping data`);
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

backup

backup(file:string): Promise<void>

以指定名称备份数据库,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
filestring备份数据库的指定名称,不能为空且长度不大于MAX_KEY_LENGTH

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

let file = "BK001";
try {
  kvStore.backup(file).then(() => {
    console.info(`Succeeded in backupping data`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to backup.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

restore

restore(file:string, callback: AsyncCallback<void>):void

从指定的数据库文件恢复数据库,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
filestring指定的数据库文件名称,不能为空且长度不大于MAX_KEY_LENGTH
callbackAsyncCallback<void>回调函数。当从指定的数据库文件恢复数据库成功,err为undefined,否则为错误对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

let file = "BK001";
try {
  kvStore.restore(file, (err) => {
    if (err) {
      console.error(`Failed to restore.code is ${err.code},message is ${err.message}`);
    } else {
      console.info(`Succeeded in restoring data`);
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

restore

restore(file:string): Promise<void>

从指定的数据库文件恢复数据库,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
filestring指定的数据库文件名称,不能为空且长度不大于MAX_KEY_LENGTH

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

let file = "BK001";
try {
  kvStore.restore(file).then(() => {
    console.info(`Succeeded in restoring data`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to restore.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

deleteBackup

deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[string, number]>>):void

根据指定名称删除备份文件,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
filesArray<string>删除备份文件所指定的名称,不能为空且长度不大于MAX_KEY_LENGTH
callbackAsyncCallback<Array<[string, number]>>回调函数,返回删除备份的文件名及其处理结果。

示例:

import { BusinessError } from '@ohos.base';

let files = ["BK001", "BK002"];
try {
  kvStore.deleteBackup(files, (err, data) => {
    if (err) {
      console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`);
    } else {
      console.info(`Succeed in deleting Backup.data=${data}`);
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

deleteBackup

deleteBackup(files:Array<string>): Promise<Array<[string, number]>>

根据指定名称删除备份文件,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
files数组<字符串>删除备份文件所指定的名称,不能为空且长度不大于MAX_KEY_LENGTH

返回值:

类型说明
Promise<Array<[string, number]>>Promise对象,返回删除备份的文件名及其处理结果。

示例:

import { BusinessError } from '@ohos.base';

let files = ["BK001", "BK002"];
try {
  kvStore.deleteBackup(files).then((data) => {
    console.info(`Succeed in deleting Backup.data=${data}`);
  }).catch((err: BusinessError) => {
    console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`);
  })
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

startTransaction

startTransaction(callback: AsyncCallback<void>): void

启动SingleKVStore数据库中的事务,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
回调AsyncCallback<void>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

function putBatchString(len: number, prefix: string) {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < len; i++) {
    let entry: distributedKVStore.Entry = {
      key: prefix + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  return entries;
} //自定义函数,放置在作用域最外侧,防止语法检查报错

try {
  let count = 0;
  kvStore.on('dataChange', 0, (data) => {
    console.info(`startTransaction 0 ${data}`);
    count++;
  });
  kvStore.startTransaction(async (err) => {
    if (err != undefined) {
      console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in starting Transaction');
    let entries = putBatchString(10, 'batch_test_string_key');
    console.info(`entries: ${entries}`);
    if (kvStore != null) {
      kvStore.putBatch(entries, async (err) => {
        if (err != undefined) {
          console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in putting Batch');
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to start Transaction.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

startTransaction

startTransaction(): Promise<void>

启动SingleKVStore数据库中的事务,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID错误信息
14800047The WAL file size exceeds the default limit.

示例:

import { BusinessError } from '@ohos.base';

try {
  let count = 0;
  kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, (data) => {
    console.info(`startTransaction 0 ${data}`);
    count++;
  });
  kvStore.startTransaction().then(async () => {
    console.info('Succeeded in starting Transaction');
  }).catch((err: BusinessError) => {
    console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to start Transaction.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

commit

commit(callback: AsyncCallback<void>): void

提交SingleKVStore数据库中的事务,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
callbackAsyncCallback<void>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  kvStore.commit((err) => {
    if (err == undefined) {
      console.info('Succeeded in committing');
    } else {
      console.error(`Failed to commit.code is ${err.code},message is ${err.message}`);
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

commit

commit(): Promise<void>

提交SingleKVStore数据库中的事务,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  kvStore.commit().then(async () => {
    console.info('Succeeded in committing');
  }).catch((err: BusinessError) => {
    console.error(`Failed to commit.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

rollback

rollback(callback: AsyncCallback<void>): void

在SingleKVStore数据库中回滚事务,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
回调AsyncCallback<void>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  kvStore.rollback((err) => {
    if (err == undefined) {
      console.info('Succeeded in rolling back');
    } else {
      console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`);
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

rollback

rollback(): Promise<void>

在SingleKVStore数据库中回滚事务,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
承诺<无效>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  kvStore.rollback().then(async () => {
    console.info('Succeeded in rolling back');
  }).catch((err: BusinessError) => {
    console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

enableSync

enableSync(enabled: boolean, callback: AsyncCallback<void>): void

设定是否开启同步,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
enabled布尔设定是否开启同步,true表示开启同步,false表示不启用同步。
回调AsyncCallback<void>回调函数。

示例:

import { BusinessError } from '@ohos.base';

try {
  kvStore.enableSync(true, (err) => {
    if (err == undefined) {
      console.info('Succeeded in enabling sync');
    } else {
      console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`);
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

enableSync

enableSync(enabled: boolean): Promise<void>

设定是否开启同步,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
enabledboolean设定是否开启同步,true表示开启同步,false表示不启用同步。

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

示例:

import { BusinessError } from '@ohos.base';

try {
  kvStore.enableSync(true).then(() => {
    console.info('Succeeded in enabling sync');
  }).catch((err: BusinessError) => {
    console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

setSyncRange

setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void

设置同步范围标签,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
localLabelsstring[]表示本地设备的同步标签。
remoteSupportLabelsstring[]表示要同步数据的设备的同步标签。
callbackAsyncCallback<void>回调函数。

示例:

import { BusinessError } from '@ohos.base';

try {
  const localLabels = ['A', 'B'];
  const remoteSupportLabels = ['C', 'D'];
  kvStore.setSyncRange(localLabels, remoteSupportLabels, (err) => {
    if (err != undefined) {
      console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in setting syncRange');
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

setSyncRange

setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void>

设置同步范围标签,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
localLabelsstring[]表示本地设备的同步标签。
remoteSupportLabelsstring[]表示要同步数据的设备的同步标签。

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

示例:

import { BusinessError } from '@ohos.base';

try {
  const localLabels = ['A', 'B'];
  const remoteSupportLabels = ['C', 'D'];
  kvStore.setSyncRange(localLabels, remoteSupportLabels).then(() => {
    console.info('Succeeded in setting syncRange');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

setSyncParam

setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void

设置数据库同步允许的默认延迟,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
defaultAllowedDelayMsnumber表示数据库同步允许的默认延迟,以毫秒为单位。
callbackAsyncCallback<void>回调函数。

示例:

import { BusinessError } from '@ohos.base';

try {
  const defaultAllowedDelayMs = 500;
  kvStore.setSyncParam(defaultAllowedDelayMs, (err) => {
    if (err != undefined) {
      console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in setting syncParam');
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

setSyncParam

setSyncParam(defaultAllowedDelayMs: number): Promise<void>

设置数据库同步允许的默认延迟,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
defaultAllowedDelayMsnumber表示数据库同步允许的默认延迟,以毫秒为单位。

返回值:

类型说明
Promise<void>无返回结果的Promise对象。

示例:

import { BusinessError } from '@ohos.base';

try {
  const defaultAllowedDelayMs = 500;
  kvStore.setSyncParam(defaultAllowedDelayMs).then(() => {
    console.info('Succeeded in setting syncParam');
  }).catch((err: BusinessError) => {
    console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

sync

sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void

在手动同步方式下,触发数据库同步。关于键值型数据库的同步方式说明,请见键值型数据库跨设备数据同步

说明:

其中deviceIds为DeviceBasicInfo中的networkId, 通过调用deviceManager.getAvailableDeviceListSync方法得到。

需要权限: ohos.permission.DISTRIBUTED_DATASYNC。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
deviceIdsstring[]同一组网环境下,需要同步的设备的networkId列表。
模式SyncMode同步模式。
delayMs可选参数,允许延时时间,单位:ms(毫秒),默认为0。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100004Not found.

示例:

import deviceManager from '@ohos.distributedDeviceManager';
import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';

let devManager: deviceManager.DeviceManager;
const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
// create deviceManager
export default class EntryAbility extends UIAbility {
  onCreate() {
    let context = this.context;
    try {
      devManager = deviceManager.createDeviceManager(context.applicationInfo.name);
      let deviceIds: string[] = [];
      if (devManager != null) {
        let devices = devManager.getAvailableDeviceListSync();
        for (let i = 0; i < devices.length; i++) {
          deviceIds[i] = devices[i].networkId as string;
        }
      }
      try {
        if (kvStore != null) {
          kvStore.on('syncComplete', (data) => {
            console.info('Sync dataChange');
          });
          if (kvStore != null) {
            kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, (err) => {
              if (err != undefined) {
                console.error(`Failed to sync.code is ${err.code},message is ${err.message}`);
                return;
              }
              console.info('Succeeded in putting data');
              const mode = distributedKVStore.SyncMode.PULL_ONLY;
              if (kvStore != null) {
                kvStore.sync(deviceIds, mode, 1000);
              }
            });
          }
        }
      } catch (e) {
        let error = e as BusinessError;
        console.error(`Failed to sync.code is ${error.code},message is ${error.message}`);
      }

    } catch (err) {
      let error = err as BusinessError;
      console.error("createDeviceManager errCode:" + error.code + ",errMessage:" + error.message);
    }
  }
}复制到剪贴板错误复制

sync

sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void

在手动同步方式下,触发数据库同步,此方法为同步方法。关于键值型数据库的同步方式说明,请见键值型数据库跨设备数据同步

说明:

其中deviceIds为DeviceBasicInfo中的networkId, 通过调用deviceManager.getAvailableDeviceListSync方法得到。

需要权限: ohos.permission.DISTRIBUTED_DATASYNC。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
deviceIdsstring[]同一组网环境下,需要同步的设备的networkId列表。
modeSyncMode同步模式。
queryQuery表示数据库的查询谓词条件
delayMsnumber可选参数,允许延时时间,单位:ms(毫秒),默认为0。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100004Not found.

示例:

import deviceManager from '@ohos.distributedDeviceManager';
import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from '@ohos.base';

let devManager: deviceManager.DeviceManager;
const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
// create deviceManager
export default class EntryAbility extends UIAbility {
  onCreate() {
    let context = this.context;
    try {
      let devManager = deviceManager.createDeviceManager(context.applicationInfo.name);
      let deviceIds: string[] = [];
      if (devManager != null) {
        let devices = devManager.getAvailableDeviceListSync();
        for (let i = 0; i < devices.length; i++) {
          deviceIds[i] = devices[i].networkId as string;
        }
      }
      try {
        if (kvStore != null) {
          kvStore.on('syncComplete', (data) => {
            console.info('Sync dataChange');
          });
          if (kvStore != null) {
            kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, (err) => {
              if (err != undefined) {
                console.error(`Failed to sync.code is ${err.code},message is ${err.message}`);
                return;
              }
              console.info('Succeeded in putting data');
              const mode = distributedKVStore.SyncMode.PULL_ONLY;
              const query = new distributedKVStore.Query();
              query.prefixKey("batch_test");
              query.deviceId(devManager.getLocalDeviceNetworkId());
              if (kvStore != null) {
                kvStore.sync(deviceIds, query, mode, 1000);
              }
            });
          }
        }
      } catch (e) {
        let error = e as BusinessError;
        console.error(`Failed to sync.code is ${error.code},message is ${error.message}`);
      }

    } catch (err) {
      let error = err as BusinessError;
      console.error("createDeviceManager errCode:" + error.code + ",errMessage:" + error.message);
    }
  }
}Copy to clipboardErrorCopied

on('dataChange')

on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void

订阅指定类型的数据变更通知。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
事件字符串订阅的事件名,固定为'dataChange',表示数据变更事件。
类型SubscribeType表示订阅的类型。
listenerCallback<ChangeNotification>回调函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, (data) => {
    console.info(`dataChange callback call data: ${data}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

on('syncComplete')

on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void

订阅同步完成事件回调通知。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
事件字符串订阅的事件名,固定为'syncComplete',表示同步完成事件。
syncCallbackCallback<Array<[string, number]>>回调函数。用于向调用方发送同步结果的回调。

示例:

import { BusinessError } from '@ohos.base';


const KEY_TEST_FLOAT_ELEMENT = 'key_test_float';
const VALUE_TEST_FLOAT_ELEMENT = 321.12;
try {
  kvStore.on('syncComplete', (data) => {
    console.info(`syncComplete ${data}`);
  });
  kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then(() => {
    console.info('succeeded in putting');
  }).catch((err: BusinessError) => {
    console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to subscribe syncComplete.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

off('dataChange')

off(event:'dataChange', listener?: Callback<ChangeNotification>): void

取消订阅数据变更通知。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
eventstring取消订阅的事件名,固定为'dataChange',表示数据变更事件。
listenerCallback<ChangeNotification>取消订阅的函数。如不设置callback,则取消所有已订阅的函数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

class KvstoreModel {
  call(data: distributedKVStore.ChangeNotification) {
    console.info(`dataChange : ${data}`);
  }

  subscribeDataChange() {
    try {
      if (kvStore != null) {
        kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call);
      }
    } catch (err) {
      let error = err as BusinessError;
      console.error(`Failed to subscribeDataChange.code is ${error.code},message is ${error.message}`);
    }
  }

  unsubscribeDataChange() {
    try {
      if (kvStore != null) {
        kvStore.off('dataChange', this.call);
      }
    } catch (err) {
      let error = err as BusinessError;
      console.error(`Failed to unsubscribeDataChange.code is ${error.code},message is ${error.message}`);
    }
  }
}Copy to clipboardErrorCopied

off('syncComplete')

off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void

取消订阅同步完成事件回调通知。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
eventstring取消订阅的事件名,固定为'syncComplete',表示同步完成事件。
syncCallbackCallback<Array<[string, number]>>取消订阅的函数。如不设置callback,则取消所有已订阅的函数。

示例:

import { BusinessError } from '@ohos.base';

class KvstoreModel {
  call(data: [string, number][]) {
    console.info(`syncComplete : ${data}`);
  }

  subscribeDataChange() {
    try {
      if (kvStore != null) {
        kvStore.on('syncComplete', this.call);
      }
    } catch (err) {
      let error = err as BusinessError;
      console.error(`Failed to subscribeDataChange.code is ${error.code},message is ${error.message}`);
    }
  }

  unsubscribeDataChange() {
    try {
      if (kvStore != null) {
        kvStore.off('syncComplete', this.call);
      }
    } catch (err) {
      let error = err as BusinessError;
      console.error(`Failed to unsubscribeDataChange.code is ${error.code},message is ${error.message}`);
    }
  } 
}Copy to clipboardErrorCopied

getSecurityLevel

getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void

获取数据库的安全级别,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
callbackAsyncCallback<SecurityLevel>回调函数。返回数据库的安全级别。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  kvStore.getSecurityLevel((err, data) => {
    if (err != undefined) {
      console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in getting securityLevel');
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getSecurityLevel

getSecurityLevel(): Promise<SecurityLevel>

获取数据库的安全级别,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

返回值:

类型说明
Promise<SecurityLevel>Promise对象。返回数据库的安全级别。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  kvStore.getSecurityLevel().then((data) => {
    console.info('Succeeded in getting securityLevel');
  }).catch((err: BusinessError) => {
    console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

DeviceKVStore

设备协同数据库,继承自SingleKVStore,提供查询数据和同步数据的方法。

设备协同数据库,以设备维度对数据进行区分,每台设备仅能写入和修改本设备的数据,其它设备的数据对其是只读的,无法修改其它设备的数据。

比如,可以使用设备协同数据库实现设备间的图片分享,可以查看其他设备的图片,但无法修改和删除其他设备的图片。

在调用DeviceKVStore的方法前,需要先通过getKVStore构建一个DeviceKVStore实例。

get

get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void

获取本设备指定键的值,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keystring要查询数据的key,不能为空且长度不大于MAX_KEY_LENGTH
callbackAsyncCallback<boolean | string | number | Uint8Array>回调函数。返回获取查询的值。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100004Not found.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
    if (err != undefined) {
      console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info("Succeeded in putting");
    if (kvStore != null) {
      kvStore.get(KEY_TEST_STRING_ELEMENT, (err, data) => {
        if (err != undefined) {
          console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info(`Succeeded in getting data.data=${data}`);
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

get

get(key: string): Promise<boolean | string | number | Uint8Array>

获取本设备指定键的值,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keystring要查询数据的key,不能为空且长度不大于MAX_KEY_LENGTH

返回值:

类型说明
Promise<Uint8Array | string | boolean | number>Promise对象。返回获取查询的值。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100004Not found.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => {
    console.info(`Succeeded in putting data`);
    if (kvStore != null) {
      kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
        console.info(`Succeeded in getting data.data=${data}`);
      }).catch((err: BusinessError) => {
        console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

get

get(deviceId: string, key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void

获取与指定设备ID和key匹配的string值,使用callback异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceIdstring标识要查询其数据的设备。
keystring表示要查询key值的键。
callbackAsyncCallback<boolean|string|number|Uint8Array>回调函数,返回匹配给定条件的字符串值。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100004Not found.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting');
    if (kvStore != null) {
      kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, (err, data) => {
        if (err != undefined) {
          console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting');
      });
    }
  })
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

get

get(deviceId: string, key: string): Promise<boolean | string | number | Uint8Array>

获取与指定设备ID和key匹配的string值,使用Promise异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceId字符串标识要查询其数据的设备。
key字符串表示要查询key值的键。

返回值:

类型说明
Promise<boolean|string|number|Uint8Array>Promise对象。返回匹配给定条件的字符串值。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100004Not found.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

const KEY_TEST_STRING_ELEMENT = 'key_test_string_2';
const VALUE_TEST_STRING_ELEMENT = 'value-string-002';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async () => {
    console.info('Succeeded in putting');
    if (kvStore != null) {
      kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => {
        console.info('Succeeded in getting');
      }).catch((err: BusinessError) => {
        console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((error: BusinessError) => {
    console.error(`Failed to put.code is ${error.code},message is ${error.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

getEntries

getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void

获取匹配本设备指定键前缀的所有键值对,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keyPrefix字符串表示要匹配的键前缀。
回调AsyncCallback<Entry[]>回调函数。返回匹配指定前缀的键值对列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  console.info(`entries: ${entries}`);
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting Batch');
    if (kvStore != null) {
      kvStore.getEntries('batch_test_string_key', (err, entries) => {
        if (err != undefined) {
          console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting Entries');
        console.info(`entries.length: ${entries.length}`);
        console.info(`entries[0]: ${entries[0]}`);
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `);
}Copy to clipboardErrorCopied

getEntries

getEntries(keyPrefix: string): Promise<Entry[]>

获取匹配本设备指定键前缀的所有键值对,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keyPrefixstring表示要匹配的键前缀。

返回值:

类型说明
Promise<Entry[]>Promise对象。返回匹配指定前缀的键值对列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  console.info(`entries: ${entries}`);
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting Batch');
    if (kvStore != null) {
      kvStore.getEntries('batch_test_string_key').then((entries) => {
        console.info('Succeeded in getting Entries');
        console.info(`PutBatch ${entries}`);
      }).catch((err: BusinessError) => {
        console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `);
}Copy to clipboardErrorCopied

getEntries

getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void

获取与指定设备ID和key前缀匹配的所有键值对,使用callback异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceIdstring标识要查询其数据的设备。
keyPrefixstring表示要匹配的键前缀。
callbackAsyncCallback<Entry[]>回调函数,返回满足给定条件的所有键值对的列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  console.info(`entries : ${entries}`);
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting batch');
    if (kvStore != null) {
      kvStore.getEntries('localDeviceId', 'batch_test_string_key', (err, entries) => {
        if (err != undefined) {
          console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting entries');
        console.info(`entries.length: ${entries.length}`);
        console.info(`entries[0]: ${entries[0]}`);
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to put batch.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getEntries

getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]>

获取与指定设备ID和key前缀匹配的所有键值对,使用Promise异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceIdstring标识要查询其数据的设备。
keyPrefixstring表示要匹配的键前缀。

返回值:

类型说明
Promise<Entry[]>Promise对象。返回匹配给定条件的所有键值对的列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  console.info(`entries: ${entries}`);
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting batch');
    if (kvStore != null) {
      kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => {
        console.info('Succeeded in getting entries');
        console.info(`entries.length: ${entries.length}`);
        console.info(`entries[0]: ${entries[0]}`);
        console.info(`entries[0].value: ${entries[0].value}`);
        console.info(`entries[0].value.value: ${entries[0].value.value}`);
      }).catch((err: BusinessError) => {
        console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to put batch.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getEntries

getEntries(query: Query, callback: AsyncCallback<Entry[]>): void

获取本设备与指定Query对象匹配的键值对列表,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示要匹配的键前缀。
callbackAsyncCallback<Entry[]>回调函数。返回本设备与指定Query对象匹配的键值对列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let arr = new Uint8Array([21, 31]);
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_bool_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.BYTE_ARRAY,
        value: arr
      }
    }
    entries.push(entry);
  }
  console.info(`entries: {entries}`);
  kvStore.putBatch(entries, async (err) => {
    console.info('Succeeded in putting Batch');
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getEntries(query, (err, entries) => {
        if (err != undefined) {
          console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting Entries');
        console.info(`entries.length: ${entries.length}`);
        console.info(`entries[0]: ${entries[0]}`);
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get Entries.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getEntries

getEntries(query: Query): Promise<Entry[]>

获取本设备与指定Query对象匹配的键值对列表,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示查询对象。

返回值:

类型说明
Promise<Entry[]>Promise对象。返回本设备与指定Query对象匹配的键值对列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let arr = new Uint8Array([21, 31]);
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_bool_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.BYTE_ARRAY,
        value: arr
      }
    }
    entries.push(entry);
  }
  console.info(`entries: {entries}`);
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting Batch');
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getEntries(query).then((entries) => {
        console.info('Succeeded in getting Entries');
      }).catch((err: BusinessError) => {
        console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`)
  });
  console.info('Succeeded in getting Entries');
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get Entries.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

getEntries

getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void

获取与指定设备ID和Query对象匹配的键值对列表,使用callback异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceId字符串键值对所属的设备ID。
queryQuery表示查询对象。
回调AsyncCallback<Entry[]>回调函数。返回与指定设备ID和Query对象匹配的键值对列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let arr = new Uint8Array([21, 31]);
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_bool_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.BYTE_ARRAY,
        value: arr
      }
    }
    entries.push(entry);
  }
  console.info(`entries: ${entries}`);
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting batch');
    let query = new distributedKVStore.Query();
    query.deviceId('localDeviceId');
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getEntries('localDeviceId', query, (err, entries) => {
        if (err != undefined) {
          console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting entries');
        console.info(`entries.length: ${entries.length}`);
        console.info(`entries[0]: ${entries[0]}`);
      })
    }
  });
  console.info('Succeeded in getting entries');
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get entries.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

getEntries

getEntries(deviceId: string, query: Query): Promise<Entry[]>

获取与指定设备ID和Query对象匹配的键值对列表,使用Promise异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceIdstring键值对所属的设备ID。
queryQuery表示查询对象。

返回值:

类型说明
Promise<Entry[]>Promise对象。返回与指定设备ID和Query对象匹配的键值对列表。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let arr = new Uint8Array([21, 31]);
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_bool_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.BYTE_ARRAY,
        value: arr
      }
    }
    entries.push(entry);
  }
  console.info(`entries: ${entries}`);
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting batch');
    let query = new distributedKVStore.Query();
    query.deviceId('localDeviceId');
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getEntries('localDeviceId', query).then((entries) => {
        console.info('Succeeded in getting entries');
      }).catch((err: BusinessError) => {
        console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
  });
  console.info('Succeeded in getting entries');
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get entries.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void

从DeviceKVStore数据库中获取本设备具有指定前缀的结果集,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keyPrefix字符串表示要匹配的键前缀。
回调AsyncCallback<KVStoreResultSet>回调函数。返回具有指定前缀的结果集。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting batch');
    if (kvStore != null) {
      kvStore.getResultSet('batch_test_string_key', async (err, result) => {
        if (err != undefined) {
          console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting result set');
        resultSet = result;
        if (kvStore != null) {
          kvStore.closeResultSet(resultSet, (err) => {
            if (err != undefined) {
              console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
              return;
            }
            console.info('Succeeded in closing result set');
          })
        }
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

getResultSet

getResultSet(keyPrefix: string): Promise<KVStoreResultSet>

从DeviceKVStore数据库中获取本设备具有指定前缀的结果集,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
keyPrefixstring表示要匹配的键前缀。

返回值:

类型说明
Promise<KVStoreResultSet>Promise对象。返回具有指定前缀的结果集。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting batch');
  }).catch((err: BusinessError) => {
    console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
  });
  kvStore.getResultSet('batch_test_string_key').then((result) => {
    console.info('Succeeded in getting result set');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet).then(() => {
        console.info('Succeeded in closing result set');
      }).catch((err: BusinessError) => {
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void

获取与指定设备ID和key前缀匹配的KVStoreResultSet对象,使用callback异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceIdstring标识要查询其数据的设备。
keyPrefixstring表示要匹配的键前缀。
callbackAsyncCallback<KVStoreResultSet>回调函数。返回与指定设备ID和key前缀匹配的KVStoreResultSet对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async (err, result) => {
    if (err != undefined) {
      console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in getting resultSet');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet, (err) => {
        if (err != undefined) {
          console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in closing resultSet');
      })
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet>

获取与指定设备ID和key前缀匹配的KVStoreResultSet对象,使用Promise异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceIdstring标识要查询其数据的设备。
keyPrefixstring表示要匹配的键前缀。

返回值:

类型说明
Promise<KVStoreResultSet>Promise对象。返回与指定设备ID和key前缀匹配的KVStoreResultSet对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => {
    console.info('Succeeded in getting resultSet');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet).then(() => {
        console.info('Succeeded in closing resultSet');
      }).catch((err: BusinessError) => {
        console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreResultSet>): void

获取与指定设备ID和Query对象匹配的KVStoreResultSet对象,使用callback异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceIdstringKVStoreResultSet对象所属的设备ID。
queryQuery表示查询对象。
callbackAsyncCallback<KVStoreResultSet>回调函数。返回与指定设备ID和Query对象匹配的KVStoreResultSet对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting batch');
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getResultSet('localDeviceId', query, async (err, result) => {
        if (err != undefined) {
          console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting resultSet');
        resultSet = result;
        if (kvStore != null) {
          kvStore.closeResultSet(resultSet, (err) => {
            if (err != undefined) {
              console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
              return;
            }
            console.info('Succeeded in closing resultSet');
          })
        }
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

getResultSet

getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet>

获取与指定设备ID和Query对象匹配的KVStoreResultSet对象,使用Promise异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceId字符串KVStoreResultSet对象所属的设备ID。
queryQuery表示查询对象。

返回值:

类型说明
Promise<KVStoreResultSet>Promise对象。返回与指定设备ID和Query对象匹配的KVStoreResultSet对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting batch');
  }).catch((err: BusinessError) => {
    console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
  });
  const query = new distributedKVStore.Query();
  query.prefixKey("batch_test");
  if (kvStore != null) {
    kvStore.getResultSet('localDeviceId', query).then((result) => {
      console.info('Succeeded in getting resultSet');
      resultSet = result;
      if (kvStore != null) {
        kvStore.closeResultSet(resultSet).then(() => {
          console.info('Succeeded in closing resultSet');
        }).catch((err: BusinessError) => {
          console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
        });
      }
    }).catch((err: BusinessError) => {
      console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
    });
  }
  query.deviceId('localDeviceId');
  console.info("GetResultSet " + query.getSqlLike());

} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

getResultSet

getResultSet(query: Query): Promise<KVStoreResultSet>

获取与本设备指定Query对象匹配的KVStoreResultSet对象,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示查询对象。

返回值:

类型说明
Promise<KVStoreResultSet>Promise对象。获取与本设备指定Query对象匹配的KVStoreResultSet对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting batch');
  }).catch((err: BusinessError) => {
    console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
  });
  const query = new distributedKVStore.Query();
  query.prefixKey("batch_test");
  kvStore.getResultSet(query).then((result) => {
    console.info('Succeeded in getting result set');
    resultSet = result;
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(query: Query, callback:AsyncCallback<KVStoreResultSet>): void

获取与本设备指定Query对象匹配的KVStoreResultSet对象,使用callback异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示查询对象。
callbackAsyncCallback<KVStoreResultSet>回调函数,获取与指定Predicates对象匹配的KVStoreResultSet对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting batch');
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getResultSet(query, async (err, result) => {
        if (err != undefined) {
          console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting resultSet');
        resultSet = result;
        if (kvStore != null) {
          kvStore.closeResultSet(resultSet, (err) => {
            if (err != undefined) {
              console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
              return;
            }
            console.info('Succeeded in closing resultSet');
          })
        }
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`);
}复制到剪贴板错误复制

getResultSet

getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void

获取与本设备指定Predicate对象匹配的KVStoreResultSet对象,使用callback异步回调。

模型约束: 此接口仅可在Stage模型下使用

系统接口: 此接口为系统接口。

系统能力: SystemCapability.DistributedDataManager.DataShare.Provider

参数:

参数名类型必填说明
predicatesdataSharePredicates.DataSharePredicates指示筛选条件,当此参数为null时,应定义处理逻辑。
回调AsyncCallback<KVStoreResultSet>回调函数,获取与指定Predicates对象匹配的KVStoreResultSet对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let predicates = new dataSharePredicates.DataSharePredicates();
  predicates.prefixKey("batch_test_string_key");
  kvStore.getResultSet(predicates, async (err, result) => {
    if (err != undefined) {
      console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in getting result set');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet, (err) => {
        if (err != undefined) {
          console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in closing result set');
      })
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}复制到剪贴板错误复制

getResultSet

getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet>

获取与本设备指定Predicate对象匹配的KVStoreResultSet对象,使用Promise异步回调。

模型约束: 此接口仅可在Stage模型下使用

系统接口: 此接口为系统接口。

系统能力: SystemCapability.DistributedDataManager.DataShare.Provider

参数:

参数名类型必填说明
predicatesdataSharePredicates.DataSharePredicates指示筛选条件,当此参数为null时,应定义处理逻辑。

返回值:

类型说明
Promise<KVStoreResultSet>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let predicates = new dataSharePredicates.DataSharePredicates();
  predicates.prefixKey("batch_test_string_key");
  kvStore.getResultSet(predicates).then((result) => {
    console.info('Succeeded in getting result set');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet).then(() => {
        console.info('Succeeded in closing result set');
      }).catch((err: BusinessError) => {
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void

获取与指定Predicate对象匹配的KVStoreResultSet对象,使用callback异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

模型约束: 此接口仅可在Stage模型下使用

系统接口: 此接口为系统接口。

系统能力: SystemCapability.DistributedDataManager.DataShare.Provider

参数:

参数名类型必填说明
deviceIdstring标识要查询其数据的设备。
predicatesdataSharePredicates.DataSharePredicates指示筛选条件,当此参数为null时,应定义处理逻辑。
callbackAsyncCallback<KVStoreResultSet>回调函数,获取与指定Predicates对象匹配的KVStoreResultSet对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let predicates = new dataSharePredicates.DataSharePredicates();
  predicates.prefixKey("batch_test_string_key");
  kvStore.getResultSet('localDeviceId', predicates, async (err, result) => {
    if (err != undefined) {
      console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in getting result set');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet, (err) => {
        if (err != undefined) {
          console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in closing result set');
      })
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

getResultSet

getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet>

获取与指定Predicate对象匹配的KVStoreResultSet对象,使用Promise异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

模型约束: 此接口仅可在Stage模型下使用

系统接口: 此接口为系统接口。

系统能力: SystemCapability.DistributedDataManager.DataShare.Provider

参数:

参数名类型必填说明
deviceIdstring标识要查询其数据的设备。
predicatesdataSharePredicates.DataSharePredicates指示筛选条件,当此参数为null时,应定义处理逻辑。

返回值:

类型说明
Promise<KVStoreResultSet>无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100001Over max limits.
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

try {
  let resultSet: distributedKVStore.KVStoreResultSet;
  let predicates = new dataSharePredicates.DataSharePredicates();
  predicates.prefixKey("batch_test_string_key");
  kvStore.getResultSet('localDeviceId', predicates).then((result) => {
    console.info('Succeeded in getting result set');
    resultSet = result;
    if (kvStore != null) {
      kvStore.closeResultSet(resultSet).then(() => {
        console.info('Succeeded in closing result set');
      }).catch((err: BusinessError) => {
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
      });
    }
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

getResultSize

getResultSize(query: Query, callback: AsyncCallback<number>): void

获取与本设备指定Query对象匹配的结果数,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示查询对象。
callbackAsyncCallback<number>回调函数。返回与本设备指定Query对象匹配的结果数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries, async (err) => {
    console.info('Succeeded in putting batch');
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getResultSize(query, async (err, resultSize) => {
        if (err != undefined) {
          console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting result set size');
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}Copy to clipboardErrorCopied

getResultSize

getResultSize(query: Query): Promise<number>

获取与本设备指定Query对象匹配的结果数,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.KVStore.Core

参数:

参数名类型必填说明
queryQuery表示查询对象。

返回值:

类型说明
Promise<number>Promise对象。获取与本设备指定Query对象匹配的结果数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting batch');
  }).catch((err: BusinessError) => {
    console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
  });
  const query = new distributedKVStore.Query();
  query.prefixKey("batch_test");
  kvStore.getResultSize(query).then((resultSize) => {
    console.info('Succeeded in getting result set size');
  }).catch((err: BusinessError) => {
    console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`);
}复制到剪贴板错误复制

getResultSize

getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void;

获取与指定设备ID和Query对象匹配的结果数,使用callback异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceId字符串KVStoreResultSet对象所属的设备ID。
queryQuery表示查询对象。
回调AsyncCallback<number>回调函数。返回与指定设备ID和Query对象匹配的结果数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries, async (err) => {
    if (err != undefined) {
      console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info('Succeeded in putting batch');
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    if (kvStore != null) {
      kvStore.getResultSize('localDeviceId', query, async (err, resultSize) => {
        if (err != undefined) {
          console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`);
          return;
        }
        console.info('Succeeded in getting resultSize');
      });
    }
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get resultSize.code is ${error.code},message is ${error.message}`);
}Copy to clipboardErrorCopied

getResultSize

getResultSize(deviceId: string, query: Query): Promise<number>

获取与指定设备ID和Query对象匹配的结果数,使用Promise异步回调。

说明:

其中deviceId通过调用deviceManager.getAvailableDeviceListSync方法得到。 deviceId具体获取方式请参考sync接口示例

系统能力: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

参数:

参数名类型必填说明
deviceIdstringKVStoreResultSet对象所属的设备ID。
queryQuery表示查询对象。

返回值:

类型说明
Promise<number>Promise对象。返回与指定设备ID和Query对象匹配的结果数。

错误码:

以下错误码的详细介绍请参见分布式键值数据库错误码

错误码ID错误信息
15100003Database corrupted.
15100005Database or result set already closed.

示例:

import { BusinessError } from '@ohos.base';

try {
  let entries: distributedKVStore.Entry[] = [];
  for (let i = 0; i < 10; i++) {
    let key = 'batch_test_string_key';
    let entry: distributedKVStore.Entry = {
      key: key + i,
      value: {
        type: distributedKVStore.ValueType.STRING,
        value: 'batch_test_string_value'
      }
    }
    entries.push(entry);
  }
  kvStore.putBatch(entries).then(async () => {
    console.info('Succeeded in putting batch');
  }).catch((err: BusinessError) => {
    console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
  });
  let query = new distributedKVStore.Query();
  query.prefixKey("batch_test");
  kvStore.getResultSize('localDeviceId', query).then((resultSize) => {
    console.info('Succeeded in getting resultSize');
  }).catch((err: BusinessError) => {
    console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`);
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get resultSize.code is ${error.code},message is ${error.message}`);
}

最后

有很多小伙伴不知道学习哪些鸿蒙开发技术?不知道需要重点掌握哪些鸿蒙应用开发知识点?而且学习时频繁踩坑,最终浪费大量时间。所以有一份实用的鸿蒙(HarmonyOS NEXT)资料用来跟着学习是非常有必要的。 

这份鸿蒙(HarmonyOS NEXT)资料包含了鸿蒙开发必掌握的核心知识要点,内容包含了ArkTS、ArkUI开发组件、Stage模型、多端部署、分布式应用开发、音频、视频、WebGL、OpenHarmony多媒体技术、Napi组件、OpenHarmony内核、Harmony南向开发、鸿蒙项目实战等等)鸿蒙(HarmonyOS NEXT)技术知识点。

希望这一份鸿蒙学习资料能够给大家带来帮助,有需要的小伙伴自行领取,限时开源,先到先得~无套路领取!!

获取这份完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习资料

鸿蒙(HarmonyOS NEXT)最新学习路线

  •  HarmonOS基础技能

  • HarmonOS就业必备技能 
  •  HarmonOS多媒体技术

  • 鸿蒙NaPi组件进阶

  • HarmonOS高级技能

  • 初识HarmonOS内核 
  • 实战就业级设备开发

有了路线图,怎么能没有学习资料呢,小编也准备了一份联合鸿蒙官方发布笔记整理收纳的一套系统性的鸿蒙(OpenHarmony )学习手册(共计1236页)鸿蒙(OpenHarmony )开发入门教学视频,内容包含:ArkTS、ArkUI、Web开发、应用模型、资源分类…等知识点。

获取以上完整版高清学习路线,请点击→纯血版全套鸿蒙HarmonyOS学习资料

《鸿蒙 (OpenHarmony)开发入门教学视频》

《鸿蒙生态应用开发V2.0白皮书》

图片

《鸿蒙 (OpenHarmony)开发基础到实战手册》

OpenHarmony北向、南向开发环境搭建

图片

 《鸿蒙开发基础》

  • ArkTS语言
  • 安装DevEco Studio
  • 运用你的第一个ArkTS应用
  • ArkUI声明式UI开发
  • .……

图片

 《鸿蒙开发进阶》

  • Stage模型入门
  • 网络管理
  • 数据管理
  • 电话服务
  • 分布式应用开发
  • 通知与窗口管理
  • 多媒体技术
  • 安全技能
  • 任务管理
  • WebGL
  • 国际化开发
  • 应用测试
  • DFX面向未来设计
  • 鸿蒙系统移植和裁剪定制
  • ……

图片

《鸿蒙进阶实战》

  • ArkTS实践
  • UIAbility应用
  • 网络案例
  • ……

图片

 获取以上完整鸿蒙HarmonyOS学习资料,请点击→纯血版全套鸿蒙HarmonyOS学习资料

总结

总的来说,华为鸿蒙不再兼容安卓,对中年程序员来说是一个挑战,也是一个机会。只有积极应对变化,不断学习和提升自己,他们才能在这个变革的时代中立于不败之地。

  • 16
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值