js-apis-distributedKVStore.md 244.3 KB
Newer Older
A
Annie_wang 已提交
1
# @ohos.data.distributedKVStore (Distributed KV Store)
A
Annie_wang 已提交
2

A
Annie_wang 已提交
3
The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. You can use the APIs provided by this module to save application data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores.
A
Annie_wang 已提交
4 5 6 7

The **distributedKVStore** module provides the following functions:

- [KVManager](#kvmanager): provides a **KVManager** instance to obtain KV store information.
A
Annie_wang 已提交
8 9 10 11
- [KVStoreResultSet](#kvstoreresultset): provides APIs for accessing the results obtained from a KV store.
- [Query](#query): provides APIs for setting predicates for data query.
- [SingleKVStore](#singlekvstore): provides APIs for querying and synchronizing data in single KV stores. The single KV stores manage data without distinguishing devices.
- [DeviceKVStore](#devicekvstore): provides APIs for querying and synchronizing data in device KV stores. This class inherits from [SingleKVStore](#singlekvstore). The device KV stores manage data by device.
A
Annie_wang 已提交
12

A
Annie_wang 已提交
13
> **NOTE**
A
Annie_wang 已提交
14 15
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
A
Annie_wang 已提交
16
> <br>All the APIs that need to obtain **deviceId** in this module are available only to system applications.
A
Annie_wang 已提交
17 18 19 20 21 22 23 24 25

## Modules to Import

```js
import distributedKVStore from '@ohos.data.distributedKVStore';
```

## KVManagerConfig

A
Annie_wang 已提交
26
Provides the **KVManager** instance configuration, including the bundle name of the invoker and the application context.
A
Annie_wang 已提交
27 28 29 30 31

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

| Name    | Type             | Mandatory| Description                                                        |
| ---------- | --------------------- | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
32
| context    | Context               | Yes  |Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).<br>Since API version 10, the type of **context** is [BaseContext](js-apis-inner-application-baseContext.md).|
A
Annie_wang 已提交
33 34 35 36 37 38 39 40 41 42
| bundleName | string                | Yes  | Bundle name.                                              |

## Constants

Provides constants of the distributed KV store.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

| Name                 | Value     | Description                                   |
| --------------------- | ------- | --------------------------------------- |
A
Annie_wang 已提交
43 44 45
| MAX_KEY_LENGTH        | 1024    | Maximum length of a key in a distributed KV store, in bytes.  |
| MAX_VALUE_LENGTH      | 4194303 | Maximum length of a value in a distributed KV store, in bytes. |
| MAX_KEY_LENGTH_DEVICE | 896     | Maximum length of a key in a device KV store, in bytes.|
A
Annie_wang 已提交
46 47 48 49 50 51
| MAX_STORE_ID_LENGTH   | 128     | Maximum length of a KV store ID, in bytes. |
| MAX_QUERY_LENGTH      | 512000  | Maximum query length, in bytes.               |
| MAX_BATCH_SIZE        | 128     | Maximum number of batch operations.                   |

## ValueType

A
Annie_wang 已提交
52
Enumerates the types of the value in a KV pair.
A
Annie_wang 已提交
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

| Name      | Description                  |
| ---------- | ---------------------- |
| STRING     | String.  |
| INTEGER    | Integer.    |
| FLOAT      | Float (single-precision floating point).  |
| BYTE_ARRAY | Byte array.|
| BOOLEAN    | Boolean.  |
| DOUBLE     | Double (double-precision floating point).|

## Value

Defines the **value** object in a KV store.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

| Name | Type  |Mandatory | Description                   |
| ----- | -------   |-----|------------------------ |
| type | [ValueType](#valuetype) | Yes|Type of the value.  |
A
Annie_wang 已提交
74
| value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair.  |
A
Annie_wang 已提交
75 76 77

## Entry

A
Annie_wang 已提交
78
Defines the KV pairs stored in a KV store.
A
Annie_wang 已提交
79 80 81 82 83

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

| Name | Type       | Mandatory| Description    |
| ----- | --------------- | ---- | -------- |
A
Annie_wang 已提交
84 85
| key   | string          | Yes  | Key of a KV pair in the KV store. |
| value | [Value](#value) | Yes  | Value of a KV pair in the KV store. |
A
Annie_wang 已提交
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129

## ChangeNotification

Defines the content of a data change notification, including inserted data, updated data, deleted data, and device ID.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

| Name         | Type         | Mandatory      | Description                    |
| ------------- | ----------------- | ---- | ------------------------ |
| insertEntries | [Entry](#entry)[] | Yes  | Data inserted.          |
| updateEntries | [Entry](#entry)[] | Yes  | Data updated.          |
| deleteEntries | [Entry](#entry)[] | Yes   | Data deleted.          |
| deviceId      | string            | Yes   | UUID of the device.|

## SyncMode

Enumerates the synchronization modes.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

| Name     | Description                                                |
| --------- | ---------------------------------------------------- |
| PULL_ONLY | Pull data from the peer end to the local end only.                      |
| PUSH_ONLY | Push data from the local end to the peer end only.                      |
| PUSH_PULL | Push data from the local end to the peer end and then pull data from the peer end to the local end.|

## SubscribeType

Enumerates the subscription types.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

| Name                 | Description                        |
| --------------------- | ---------------------------- |
| SUBSCRIBE_TYPE_LOCAL  | Local data changes.      |
| SUBSCRIBE_TYPE_REMOTE | Remote data changes.      |
| SUBSCRIBE_TYPE_ALL    | Local and remote data changes.|

## KVStoreType

Enumerates the distributed KV store types.

| Name                | Description                                                        |
| -------------------- | ------------------------------------------------------------ |
A
Annie_wang 已提交
130
| DEVICE_COLLABORATION | Device KV store.<br>The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|
A
Annie_wang 已提交
131
| SINGLE_VERSION       | Single KV store.<br>The single KV store does not differentiate data by device. If entries with the same key are modified on different devices, the value will be overwritten.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
A
Annie_wang 已提交
132 133 134 135 136 137 138

## SecurityLevel

Enumerates the KV store security levels.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

A
Annie_wang 已提交
139
| Name       | Description                                                        |
A
Annie_wang 已提交
140 141 142 143 144
| ---: | ------------------------------------------------------------ |
|   S1 | Low security level. Disclosure, tampering, corruption, or loss of the data may cause minor impact on an individual or group.<br>Examples: gender and nationality information, and user application records |
|   S2 | Medium security level. Disclosure, tampering, corruption, or loss of the data may cause major impact on an individual or group.<br>Examples: mailing addresses and nicknames of individuals |
|   S3 | High security level. Disclosure, tampering, corruption, or loss of the data may cause critical impact on an individual or group.<br>Examples: real-time precise positioning information and movement trajectory |
|   S4 | Critical security level. Disclosure, tampering, corruption, or loss of the data may cause significant adverse impact on an individual or group.<br>Examples: political opinions, religious and philosophical belief, trade union membership, genetic data, biological information, health and sexual life status, sexual orientation, device authentication, and personal credit card information |
A
Annie_wang 已提交
145 146 147 148 149 150 151 152

## Options

Provides KV store configuration.

| Name         | Type                       | Mandatory| Description                                                        |
| --------------- | -------------- | ---- | -------------------------|
| createIfMissing | boolean                         | No | Whether to create a KV store if no database file exists. By default, a KV store is created.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core|
A
Annie_wang 已提交
153
| encrypt         | boolean                         | No  | Whether to encrypt the KV store. By default, KV stores are not encrypted.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
A
Annie_wang 已提交
154
| backup          | boolean                         | No  | Whether to back up database files. By default, database files are backed up. <br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core|
A
Annie_wang 已提交
155 156
| autoSync        | boolean                         | No  | Whether to automatically synchronize the KV store data. The value **true** means to automatically synchronize the KV store data; the value **false** (default) means the opposite.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core<br>**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC |
| kvStoreType     | [KVStoreType](#kvstoretype)     | No  | Type of the KV store to create. By default, a device KV store is created.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core |
A
Annie_wang 已提交
157 158 159 160 161 162 163 164 165 166 167 168
| securityLevel   | [SecurityLevel](#securitylevel) | Yes  |Security level of the KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core|
| schema          | [Schema](#schema)               | No  | Schema used to define the values stored in the KV store. By default, **schema** is not used.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore|

## Schema

Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store.

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

| Name   | Type                   | Readable| Writable| Description                      |
| ------- | ----------------------- | ---- | ---- | -------------------------- |
| root    | [FieldNode](#fieldnode) | Yes  | Yes  | JSON root object.          |
A
Annie_wang 已提交
169
| indexes | Array\<string>          | Yes  | Yes  | Array of strings in JSON format. |
A
Annie_wang 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
| mode    | number                  | Yes  | Yes  | Schema mode.        |
| skip    | number                  | Yes  | Yes  | Size of a skip of the schema.        |

### constructor

constructor()

A constructor used to create a **Schema** instance.

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

## FieldNode

Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store.

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

| Name    | Type   | Readable| Writable| Description                          |
| -------- | ------- | ---- | ---- | ------------------------------ |
| nullable | boolean | Yes  | Yes  | Whether the database field can be null.  |
| default  | string  | Yes  | Yes  | Default value of a **FieldNode**.       |
| type     | number  | Yes  | Yes  | Value of the data type corresponding to the specified node.|

### constructor

constructor(name: string)

A constructor used to create a **FieldNode** instance with a string field.

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name| Type| Mandatory| Description           |
| ------ | -------- | ---- | --------------- |
| name   | string   | Yes  | Value of **FieldNode**.|

### appendChild

appendChild(child: FieldNode): boolean

Appends a child node to this **FieldNode**.

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name| Type               | Mandatory| Description            |
| ------ | ----------------------- | ---- | ---------------- |
| child  | [FieldNode](#fieldnode) | Yes  | Child node to append.|

**Return value**

| Type   | Description                                                        |
| ------- | ------------------------------------------------------------ |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|

**Example**

```js

try {
A
Annie_wang 已提交
232 233 234 235
    let node = new distributedKVStore.FieldNode("root");
    let child1 = new distributedKVStore.FieldNode("child1");
    let child2 = new distributedKVStore.FieldNode("child2");
    let child3 = new distributedKVStore.FieldNode("child3");
A
Annie_wang 已提交
236 237 238
    node.appendChild(child1);
    node.appendChild(child2);
    node.appendChild(child3);
A
Annie_wang 已提交
239
    console.info("appendNode " + JSON.stringify(node));
A
Annie_wang 已提交
240 241 242 243 244
    child1 = null;
    child2 = null;
    child3 = null;
    node = null;
} catch (e) {
A
Annie_wang 已提交
245
    console.error("AppendChild " + e);
A
Annie_wang 已提交
246 247 248 249 250
}
```

## distributedKVStore.createKVManager

A
Annie_wang 已提交
251
createKVManager(config: KVManagerConfig): KVManager
A
Annie_wang 已提交
252

A
Annie_wang 已提交
253
Creates a **KVManager** instance for KV store management.
A
Annie_wang 已提交
254 255 256 257 258 259 260

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type                     | Mandatory| Description                                                     |
| ------ | ----------------------------- | ---- | --------------------------------------------------------- |
A
Annie_wang 已提交
261
| config | [KVManagerConfig](#kvmanagerconfig) | Yes  | **KVManager** instance configuration, including the bundle name and user information of the caller.|
A
Annie_wang 已提交
262 263 264 265 266

**Return value**

| Type                                  | Description                                      |
| -------------------------------------- | ------------------------------------------ |
A
Annie_wang 已提交
267
| [KVManager](#kvmanager) | **KVManager** instance created.|
A
Annie_wang 已提交
268 269 270 271 272 273

**Example**

Stage model:

```js
A
Annie_wang 已提交
274 275
import UIAbility from '@ohos.app.ability.UIAbility';

A
Annie_wang 已提交
276
let kvManager;
A
Annie_wang 已提交
277
export default class EntryAbility extends UIAbility {
A
Annie_wang 已提交
278
    onCreate() {
A
Annie_wang 已提交
279
        console.info("MyAbilityStage onCreate")
A
Annie_wang 已提交
280 281 282 283 284 285
        let context = this.context
        const kvManagerConfig = {
            context: context,
            bundleName: 'com.example.datamanagertest',
        }
        try {
A
Annie_wang 已提交
286
            kvManager = distributedKVStore.createKVManager(kvManagerConfig);
A
Annie_wang 已提交
287
            console.info("Succeeded in creating KVManager");
A
Annie_wang 已提交
288 289 290 291 292 293 294 295 296 297
        } catch (e) {
            console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`);
        }
    }
}
```

FA model:

```js
A
Annie_wang 已提交
298
import featureAbility from '@ohos.ability.featureAbility';
A
Annie_wang 已提交
299 300 301 302 303 304 305
let kvManager;
let context = featureAbility.getContext()
const kvManagerConfig = {
    context: context,
    bundleName: 'com.example.datamanagertest',
}
try {
A
Annie_wang 已提交
306
    kvManager = distributedKVStore.createKVManager(kvManagerConfig);
A
Annie_wang 已提交
307
    console.info("Succeeded in creating KVManager");
A
Annie_wang 已提交
308 309 310 311 312 313 314 315 316 317 318
} catch (e) {
    console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`);
}
```

## KVManager

Provides an instance to obtain information about a distributed KV store. Before calling any API in **KVManager**, you must use [createKVManager](#distributedkvstorecreatekvmanager) to create a **KVManager** instance.

### getKVStore

A
Annie_wang 已提交
319
getKVStore&lt;T&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void
A
Annie_wang 已提交
320 321 322 323 324 325 326 327 328 329 330

Creates and obtains a distributed KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type              | Mandatory| Description                                                        |
| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
| storeId  | string                 | Yes  | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
| options  | [Options](#options)    | Yes  | Configuration of the KV store to create.                              |
A
Annie_wang 已提交
331
| callback | AsyncCallback&lt;T&gt; | Yes  | Callback invoked to return the **SingleKVStore** or **DeviceKVStore** instance created.|
A
Annie_wang 已提交
332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

| ID| **Error Message**                               |
| ------------ | ------------------------------------------- |
| 15100002     | Open existed database with changed options. |
| 15100003     | Database corrupted.                         |

**Example**

```js
let kvStore;
try {
    const options = {
        createIfMissing: true,
        encrypt: false,
        backup: false,
        autoSync: true,
        kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
        securityLevel: distributedKVStore.SecurityLevel.S2,
    };
    kvManager.getKVStore('storeId', options, function (err, store) {
        if (err) {
A
Annie_wang 已提交
357
            console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
358 359
            return;
        }
A
Annie_wang 已提交
360
        console.info("Succeeded in getting KVStore");
A
Annie_wang 已提交
361 362 363
        kvStore = store;
    });
} catch (e) {
A
Annie_wang 已提交
364
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
365 366 367 368 369
}
```

### getKVStore

A
Annie_wang 已提交
370
getKVStore&lt;T&gt;(storeId: string, options: Options): Promise&lt;T&gt;
A
Annie_wang 已提交
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386

Creates and obtains a distributed KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name | Type           | Mandatory| Description                                                        |
| ------- | ------------------- | ---- | ------------------------------------------------------------ |
| storeId | string              | Yes  | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
| options | [Options](#options) | Yes  | Configuration of the distributed KV store to create.                              |

**Return value**

| Type            | Description                                                        |
| ---------------- | ------------------------------------------------------------ |
A
Annie_wang 已提交
387
| Promise&lt;T&gt; | Promise used to return the **SingleKVStore** or **DeviceKVStore** instance created.|
A
Annie_wang 已提交
388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

| ID| **Error Message**                               |
| ------------ | ------------------------------------------- |
| 15100002     | Open existed database with changed options. |
| 15100003     | Database corrupted.                         |

**Example**

```js
let kvStore;
try {
    const options = {
        createIfMissing: true,
        encrypt: false,
        backup: false,
        autoSync: true,
        kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
        securityLevel: distributedKVStore.SecurityLevel.S2,
    };
    kvManager.getKVStore('storeId', options).then((store) => {
A
Annie_wang 已提交
412
        console.info("Succeeded in getting KVStore");
A
Annie_wang 已提交
413 414
        kvStore = store;
    }).catch((err) => {
A
Annie_wang 已提交
415
        console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
416 417
    });
} catch (e) {
A
Annie_wang 已提交
418
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451
}
```

### closeKVStore

closeKVStore(appId: string, storeId: string, callback: AsyncCallback&lt;void&gt;): void

Closes a distributed KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                 | Mandatory| Description                                                        |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| appId    | string                    | Yes  | Bundle name of the app that invokes the KV store.                                      |
| storeId  | string                    | Yes  | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.                                                  |

**Example**

```js
const options = {
    createIfMissing: true,
    encrypt: false,
    backup: false,
    autoSync: true,
    kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
    schema: '',
    securityLevel: distributedKVStore.SecurityLevel.S2,
}
try {
    kvManager.getKVStore('storeId', options, async function (err, store) {
A
Annie_wang 已提交
452 453 454 455 456
        if (err != undefined) {
            console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
            return;
        }
        console.info('Succeeded in getting KVStore');
A
Annie_wang 已提交
457
        kvStore = store;
A
Annie_wang 已提交
458 459
        kvStore = null;
        store = null;
A
Annie_wang 已提交
460 461
        kvManager.closeKVStore('appId', 'storeId', function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
462
                console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
463 464
                return;
            }
A
Annie_wang 已提交
465
            console.info('Succeeded in closing KVStore');
A
Annie_wang 已提交
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
        });
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### closeKVStore

closeKVStore(appId: string, storeId: string): Promise&lt;void&gt;

Closes a distributed KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name | Type| Mandatory| Description                                                        |
| ------- | -------- | ---- | ------------------------------------------------------------ |
| appId   | string   | Yes  | Bundle name of the app that invokes the KV store.                                      |
| storeId | string   | Yes  | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|

**Return value**

| Type          | Description                     |
| -------------- | ------------------------- |
| Promise\<void> | Promise that returns no value.|

**Example**

```js
const options = {
    createIfMissing: true,
    encrypt: false,
    backup: false,
    autoSync: true,
    kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
    schema: '',
    securityLevel: distributedKVStore.SecurityLevel.S2,
}
try {
    kvManager.getKVStore('storeId', options).then(async (store) => {
A
Annie_wang 已提交
508
        console.info('Succeeded in getting KVStore');
A
Annie_wang 已提交
509
        kvStore = store;
A
Annie_wang 已提交
510 511
        kvStore = null;
        store = null;
A
Annie_wang 已提交
512
        kvManager.closeKVStore('appId', 'storeId').then(() => {
A
Annie_wang 已提交
513
            console.info('Succeeded in closing KVStore');
A
Annie_wang 已提交
514
        }).catch((err) => {
A
Annie_wang 已提交
515
            console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
516 517
        });
    }).catch((err) => {
A
Annie_wang 已提交
518
        console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
519 520
    });
} catch (e) {
A
Annie_wang 已提交
521
    console.error(`Failed to close KVStore.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
}
```

### deleteKVStore

deleteKVStore(appId: string, storeId: string, callback: AsyncCallback&lt;void&gt;): void

Deletes a distributed KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                 | Mandatory| Description                                                        |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| appId    | string                    | Yes  | Bundle name of the app that invokes the KV store.                                      |
| storeId  | string                    | Yes  | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.                                                  |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
545
| ID| **Error Message**|
A
Annie_wang 已提交
546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
| ------------ | ------------ |
| 15100004     | Not found.   |

**Example**

```js
const options = {
    createIfMissing: true,
    encrypt: false,
    backup: false,
    autoSync: true,
    kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
    schema: '',
    securityLevel: distributedKVStore.SecurityLevel.S2,
}
try {
    kvManager.getKVStore('store', options, async function (err, store) {
        if (err != undefined) {
A
Annie_wang 已提交
564
            console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
565 566
            return;
        }
A
Annie_wang 已提交
567
        console.info('Succeeded in getting KVStore');
A
Annie_wang 已提交
568
        kvStore = store;
A
Annie_wang 已提交
569 570
        kvStore = null;
        store = null;
A
Annie_wang 已提交
571 572
        kvManager.deleteKVStore('appId', 'storeId', function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
573
                console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
574 575
                return;
            }
A
Annie_wang 已提交
576
            console.info(`Succeeded in deleting KVStore`);
A
Annie_wang 已提交
577 578 579
        });
    });
} catch (e) {
A
Annie_wang 已提交
580
    console.error(`Failed to delete KVStore.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608
}
```

### deleteKVStore

deleteKVStore(appId: string, storeId: string): Promise&lt;void&gt;

Deletes a distributed KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name | Type| Mandatory| Description                                                        |
| ------- | -------- | ---- | ------------------------------------------------------------ |
| appId   | string   | Yes  | Bundle name of the app that invokes the KV store.                                      |
| storeId | string   | Yes  | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).|

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
609
| ID| **Error Message**|
A
Annie_wang 已提交
610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
| ------------ | ------------ |
| 15100004     | Not found.   |

**Example**

```js
const options = {
    createIfMissing: true,
    encrypt: false,
    backup: false,
    autoSync: true,
    kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
    schema: '',
    securityLevel: distributedKVStore.SecurityLevel.S2,
}
try {
    kvManager.getKVStore('storeId', options).then(async (store) => {
A
Annie_wang 已提交
627
        console.info('Succeeded in getting KVStore');
A
Annie_wang 已提交
628
        kvStore = store;
A
Annie_wang 已提交
629 630
        kvStore = null;
        store = null;
A
Annie_wang 已提交
631
        kvManager.deleteKVStore('appId', 'storeId').then(() => {
A
Annie_wang 已提交
632
            console.info('Succeeded in deleting KVStore');
A
Annie_wang 已提交
633
        }).catch((err) => {
A
Annie_wang 已提交
634
            console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
635 636
        });
    }).catch((err) => {
A
Annie_wang 已提交
637
        console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
638 639
    });
} catch (e) {
A
Annie_wang 已提交
640
    console.error(`Failed to delete KVStore.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
641 642 643 644 645 646 647
}
```

### getAllKVStoreId

getAllKVStoreId(appId: string, callback: AsyncCallback&lt;string[]&gt;): void

A
Annie_wang 已提交
648
Obtains IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
649 650 651 652 653 654 655 656

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                     | Mandatory| Description                                               |
| -------- | ----------------------------- | ---- | --------------------------------------------------- |
| appId    | string                        | Yes  | Bundle name of the app that invokes the KV store.                             |
A
Annie_wang 已提交
657
| callback | AsyncCallback&lt;string[]&gt; | Yes  | Callback invoked to return the IDs of all the distributed KV stores created.|
A
Annie_wang 已提交
658 659 660 661 662 663 664

**Example**

```js
try {
    kvManager.getAllKVStoreId('appId', function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
665
            console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
666 667
            return;
        }
A
Annie_wang 已提交
668 669
        console.info('Succeeded in getting AllKVStoreId');
        console.info(`GetAllKVStoreId size = ${data.length}`);
A
Annie_wang 已提交
670 671
    });
} catch (e) {
A
Annie_wang 已提交
672
    console.error(`Failed to get AllKVStoreId.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
673 674 675 676 677 678 679
}
```

### getAllKVStoreId

getAllKVStoreId(appId: string): Promise&lt;string[]&gt;

A
Annie_wang 已提交
680
Obtains IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses a promise to return the result.
A
Annie_wang 已提交
681 682 683 684 685 686 687 688 689 690 691 692 693

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                  |
| ------ | -------- | ---- | ---------------------- |
| appId  | string   | Yes  | Bundle name of the app that invokes the KV store.|

**Return value**

| Type                   | Description                                                  |
| ----------------------- | ------------------------------------------------------ |
A
Annie_wang 已提交
694
| Promise&lt;string[]&gt; | Promise used to return IDs of all the distributed KV stores created. |
A
Annie_wang 已提交
695 696 697 698 699

**Example**

```js
try {
A
Annie_wang 已提交
700
    console.info('GetAllKVStoreId');
A
Annie_wang 已提交
701
    kvManager.getAllKVStoreId('appId').then((data) => {
A
Annie_wang 已提交
702 703
        console.info('Succeeded in getting AllKVStoreId');
        console.info(`GetAllKVStoreId size = ${data.length}`);
A
Annie_wang 已提交
704
    }).catch((err) => {
A
Annie_wang 已提交
705
        console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
706 707
    });
} catch (e) {
A
Annie_wang 已提交
708
    console.error(`Failed to get AllKVStoreId.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
709 710 711 712 713 714 715
}
```

### on('distributedDataServiceDie')

on(event: 'distributedDataServiceDie', deathCallback: Callback&lt;void&gt;): void

A
Annie_wang 已提交
716
Subscribes to service status changes. If a service is terminated, you need to register the callbacks for data change notifications and synchronization complete notifications again. In addition, an error will be returned for a synchronization operation.
A
Annie_wang 已提交
717 718 719 720 721 722 723 724

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name       | Type            | Mandatory| Description                                                        |
| ------------- | -------------------- | ---- | ------------------------------------------------------------ |
| event         | string               | Yes  | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.|
A
Annie_wang 已提交
725
| deathCallback | Callback&lt;void&gt; | Yes  | Callback invoked to return service status changes.                                                  |
A
Annie_wang 已提交
726 727 728 729 730

**Example**

```js
try {
A
Annie_wang 已提交
731
    console.info('KVManagerOn');
A
Annie_wang 已提交
732
    const deathCallback = function () {
A
Annie_wang 已提交
733
        console.info('death callback call');
A
Annie_wang 已提交
734 735 736
    }
    kvManager.on('distributedDataServiceDie', deathCallback);
} catch (e) {
A
Annie_wang 已提交
737
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
738 739 740 741 742 743 744
}
```

### off('distributedDataServiceDie')

off(event: 'distributedDataServiceDie', deathCallback?: Callback&lt;void&gt;): void

A
Annie_wang 已提交
745
Unsubscribes from service status changes. The **deathCallback** parameter must be a callback registered for subscribing to service status changes. Otherwise, the unsubscription will fail.
A
Annie_wang 已提交
746 747 748 749 750 751 752 753

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name       | Type            | Mandatory| Description                                                        |
| ------------- | -------------------- | ---- | ------------------------------------------------------------ |
| event         | string               | Yes  | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates a service status change event.|
A
Annie_wang 已提交
754
| deathCallback | Callback&lt;void&gt; | No  | Callback for the service status change event. If this parameter is not specified, all deathCallback subscriptions will be canceled.                                         |
A
Annie_wang 已提交
755 756 757 758 759

**Example**

```js
try {
A
Annie_wang 已提交
760
    console.info('KVManagerOff');
A
Annie_wang 已提交
761
    const deathCallback = function () {
A
Annie_wang 已提交
762
        console.info('death callback call');
A
Annie_wang 已提交
763 764 765
    }
    kvManager.off('distributedDataServiceDie', deathCallback);
} catch (e) {
A
Annie_wang 已提交
766
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
767 768 769 770 771
}
```

## KVStoreResultSet

A
Annie_wang 已提交
772
Provides APIs for obtaining the distributed KV store result sets. A maximum of eight result sets can be opened at a time.
A
Annie_wang 已提交
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794

Before calling any API in **KVStoreResultSet**, you must use **[getKVStore](#getkvstore)** to construct a **SingleKVStore** or **DeviceKVStore** instance.

### getCount

getCount(): number

Obtains the total number of rows in the result set.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type  | Description              |
| ------ | ------------------ |
| number | Total number of rows obtained.|

**Example**

```js
try {
    let resultSet;
A
Annie_wang 已提交
795
    let count;
A
Annie_wang 已提交
796
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
797
        console.info('getResultSet succeed.');
A
Annie_wang 已提交
798
        resultSet = result;
A
Annie_wang 已提交
799 800
        count = resultSet.getCount();
        console.info("getCount succeed:" + count);
A
Annie_wang 已提交
801
    }).catch((err) => {
A
Annie_wang 已提交
802
        console.error('getResultSet failed: ' + err);
A
Annie_wang 已提交
803 804
    });
} catch (e) {
A
Annie_wang 已提交
805
    console.error("getCount failed: " + e);
A
Annie_wang 已提交
806 807 808 809 810 811 812
}
```

### getPosition

getPosition(): number

A
Annie_wang 已提交
813
Obtains the current data read position (position from which data is read) in the result set. The read position changes with the operations, such as [moveToFirst](#movetofirst) and [moveToLast](#movetolast).
A
Annie_wang 已提交
814 815 816 817 818 819 820

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type  | Description              |
| ------ | ------------------ |
A
Annie_wang 已提交
821
| number | Current data read position obtained. The value must be greater than or equal to **-1**. The value **-1** means no data is read; the value **0** indicates the first row.|
A
Annie_wang 已提交
822 823 824 825 826 827

**Example**

```js
try {
    let resultSet;
A
Annie_wang 已提交
828
    let position;
A
Annie_wang 已提交
829
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
830
        console.info('getResultSet succeeded.');
A
Annie_wang 已提交
831
        resultSet = result;
A
Annie_wang 已提交
832 833
        position = resultSet.getPosition();
        console.info("getPosition succeed:" + position);
A
Annie_wang 已提交
834
    }).catch((err) => {
A
Annie_wang 已提交
835
        console.error('getResultSet failed: ' + err);
A
Annie_wang 已提交
836 837
    });
} catch (e) {
A
Annie_wang 已提交
838
    console.error("getPosition failed: " + e);
A
Annie_wang 已提交
839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860
}
```

### moveToFirst

moveToFirst(): boolean

Moves the data read position to the first row. If the result set is empty, **false** will be returned.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type   | Description                                           |
| ------- | ----------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|

**Example**

```js
try {
    let resultSet;
A
Annie_wang 已提交
861
    let moved;
A
Annie_wang 已提交
862
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
863
        console.info('getResultSet succeed.');
A
Annie_wang 已提交
864
        resultSet = result;
A
Annie_wang 已提交
865 866
        moved = resultSet.moveToFirst();
        console.info("moveToFirst succeed: " + moved);
A
Annie_wang 已提交
867
    }).catch((err) => {
A
Annie_wang 已提交
868
        console.error('getResultSet failed: ' + err);
A
Annie_wang 已提交
869 870
    });
} catch (e) {
A
Annie_wang 已提交
871
    console.error("moveToFirst failed " + e);
A
Annie_wang 已提交
872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893
}
```

### moveToLast

moveToLast(): boolean

Moves the data read position to the last row. If the result set is empty, **false** will be returned.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type   | Description                                           |
| ------- | ----------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|

**Example**

```js
try {
    let resultSet;
A
Annie_wang 已提交
894
    let moved;
A
Annie_wang 已提交
895
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
896
        console.info('getResultSet succeed.');
A
Annie_wang 已提交
897
        resultSet = result;
A
Annie_wang 已提交
898 899
        moved = resultSet.moveToLast();
        console.info("moveToLast succeed:" + moved);
A
Annie_wang 已提交
900
    }).catch((err) => {
A
Annie_wang 已提交
901
        console.error('getResultSet failed: ' + err);
A
Annie_wang 已提交
902 903
    });
} catch (e) {
A
Annie_wang 已提交
904
    console.error("moveToLast failed: " + e);
A
Annie_wang 已提交
905 906 907 908 909 910 911
}
```

### moveToNext

moveToNext(): boolean

A
Annie_wang 已提交
912
Moves the data read position to the next row. If the result set is empty, **false** will be returned. This API applies when the whole result set is obtained.
A
Annie_wang 已提交
913 914 915 916 917 918 919 920 921 922 923 924 925 926

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type   | Description                                           |
| ------- | ----------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|

**Example**

```js
try {
    let resultSet;
A
Annie_wang 已提交
927
    let moved;
A
Annie_wang 已提交
928
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
929
        console.info('getResultSet succeed.');
A
Annie_wang 已提交
930
        resultSet = result;
A
Annie_wang 已提交
931 932 933 934 935
        do {
          moved = resultSet.moveToNext();
          const entry  = resultSet.getEntry();
          console.info("moveToNext succeed: " + moved);
        } while (moved)
A
Annie_wang 已提交
936
    }).catch((err) => {
A
Annie_wang 已提交
937
        console.error('getResultSet failed: ' + err);
A
Annie_wang 已提交
938 939
    });
} catch (e) {
A
Annie_wang 已提交
940
    console.error("moveToNext failed: " + e);
A
Annie_wang 已提交
941 942 943 944 945 946 947
}
```

### moveToPrevious

moveToPrevious(): boolean

A
Annie_wang 已提交
948
Moves the data read position to the previous row. If the result set is empty, **false** will be returned. This API applies when the whole result set is obtained.
A
Annie_wang 已提交
949 950 951 952 953 954 955 956 957 958 959 960 961 962

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type   | Description                                           |
| ------- | ----------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|

**Example**

```js
try {
    let resultSet;
A
Annie_wang 已提交
963
    let moved;
A
Annie_wang 已提交
964
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
965
        console.info('getResultSet succeed.');
A
Annie_wang 已提交
966
        resultSet = result;
A
Annie_wang 已提交
967 968 969
        moved = resultSet.moveToLast();
        moved = resultSet.moveToPrevious();
        console.info("moveToPrevious succeed:" + moved);
A
Annie_wang 已提交
970
    }).catch((err) => {
A
Annie_wang 已提交
971
        console.error('getResultSet failed: ' + err);
A
Annie_wang 已提交
972 973
    });
} catch (e) {
A
Annie_wang 已提交
974
    console.error("moveToPrevious failed: " + e);
A
Annie_wang 已提交
975 976 977 978 979 980 981
}
```

### move

move(offset: number): boolean

A
Annie_wang 已提交
982
Moves the data read position with the specified offset from the current position. That is, move the number of rows specified by **offset** from the current position.
A
Annie_wang 已提交
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                                                        |
| ------ | -------- | ---- | ------------------------------------------------------------ |
| offset | number   | Yes  | Offset to move the data read position. A negative value means to move backward, and a positive value means to move forward.|

**Return value**

| Type   | Description                                           |
| ------- | ----------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|

**Example**

```js
try {
    let resultSet;
A
Annie_wang 已提交
1003
    let moved;
A
Annie_wang 已提交
1004
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
1005
        console.info('Succeeded in getting resultSet');
A
Annie_wang 已提交
1006
        resultSet = result;
A
Annie_wang 已提交
1007 1008
        moved = resultSet.move(2); // If the current position is 0, move the read position forward by two rows, that is, move to row 3.
        console.info(`Succeeded in moving.moved = ${moved}`);
A
Annie_wang 已提交
1009
    }).catch((err) => {
A
Annie_wang 已提交
1010
        console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
1011 1012
    });
} catch (e) {
A
Annie_wang 已提交
1013
    console.error(`Failed to move.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
}
```

### moveToPosition

moveToPosition(position: number): boolean

Moves the data read position from 0 to an absolute position.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type| Mandatory| Description          |
| -------- | -------- | ---- | -------------- |
| position | number   | Yes  | Absolute position to move to.|

**Return value**

| Type   | Description                                           |
| ------- | ----------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|

**Example**

```js
try {
    let resultSet;
A
Annie_wang 已提交
1042
    let moved;
A
Annie_wang 已提交
1043
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
1044
        console.info('Succeeded in getting resultSet');
A
Annie_wang 已提交
1045
        resultSet = result;
A
Annie_wang 已提交
1046 1047
        moved = resultSet.moveToPosition(1);
        console.info(`Succeeded in moving to position.moved=${moved}`);
A
Annie_wang 已提交
1048
    }).catch((err) => {
A
Annie_wang 已提交
1049
        console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
1050 1051
    });
} catch (e) {
A
Annie_wang 已提交
1052
    console.error(`Failed to move to position.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074
}
```

### isFirst

isFirst(): boolean

Checks whether the data read position is the first row.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type   | Description                                                        |
| ------- | ------------------------------------------------------------ |
| boolean | Returns **true** if the first row is being read; returns **false** otherwise.|

**Example**

```js
try {
    let resultSet;
A
Annie_wang 已提交
1075
    let isfirst;
A
Annie_wang 已提交
1076
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
1077
        console.info('getResultSet succeed.');
A
Annie_wang 已提交
1078
        resultSet = result;
A
Annie_wang 已提交
1079 1080
        isfirst = resultSet.isFirst();
        console.info("Check isFirst succeed:" + isfirst);
A
Annie_wang 已提交
1081
    }).catch((err) => {
A
Annie_wang 已提交
1082
        console.error('getResultSet failed: ' + err);
A
Annie_wang 已提交
1083 1084
    });
} catch (e) {
A
Annie_wang 已提交
1085
    console.error("Check isFirst failed: " + e);
A
Annie_wang 已提交
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107
}
```

### isLast

isLast(): boolean

Checks whether the data read position is the last row.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type   | Description                                                        |
| ------- | ------------------------------------------------------------ |
| boolean | Returns **true** if the last row is being read; returns **false** otherwise.|

**Example**

```js
try {
    let resultSet;
A
Annie_wang 已提交
1108
    let islast;
A
Annie_wang 已提交
1109
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
1110
        console.info('getResultSet succeed.');
A
Annie_wang 已提交
1111
        resultSet = result;
A
Annie_wang 已提交
1112 1113
        islast = resultSet.isLast();
        console.info("Check isLast succeed: " + islast);
A
Annie_wang 已提交
1114
    }).catch((err) => {
A
Annie_wang 已提交
1115
        console.error('getResultSet failed: ' + err);
A
Annie_wang 已提交
1116 1117
    });
} catch (e) {
A
Annie_wang 已提交
1118
    console.error("Check isLast failed: " + e);
A
Annie_wang 已提交
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141
}
```

### isBeforeFirst

isBeforeFirst(): boolean

Checks whether the data read position is before the first row.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type   | Description                                                        |
| ------- | ------------------------------------------------------------ |
| boolean | Returns **true** if the data read position is before the first row; returns **false** otherwise.|

**Example**

```js
try {
    let resultSet;
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
1142
        console.info('getResultSet succeed.');
A
Annie_wang 已提交
1143
        resultSet = result;
A
Annie_wang 已提交
1144 1145
        const isbeforefirst = resultSet.isBeforeFirst();
        console.info("Check isBeforeFirst succeed: " + isbeforefirst);
A
Annie_wang 已提交
1146
    }).catch((err) => {
A
Annie_wang 已提交
1147
        console.error('getResultSet failed: ' + err);
A
Annie_wang 已提交
1148 1149
    });
} catch (e) {
A
Annie_wang 已提交
1150
    console.error("Check isBeforeFirst failed: " + e);
A
Annie_wang 已提交
1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
}
```

### isAfterLast

isAfterLast(): boolean

Checks whether the data read position is after the last row.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type   | Description                                                        |
| ------- | ------------------------------------------------------------ |
| boolean | Returns **true** if the data read position is after the last row; returns **false** otherwise.|

**Example**

```js
try {
    let resultSet;
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
1174
        console.info('getResultSet succeed.');
A
Annie_wang 已提交
1175
        resultSet = result;
A
Annie_wang 已提交
1176 1177
        const isafterlast = resultSet.isAfterLast();
        console.info("Check isAfterLast succeed:" + isafterlast);
A
Annie_wang 已提交
1178
    }).catch((err) => {
A
Annie_wang 已提交
1179
        console.error('getResultSet failed: ' + err);
A
Annie_wang 已提交
1180 1181
    });
} catch (e) {
A
Annie_wang 已提交
1182
    console.error("Check isAfterLast failed: " + e);
A
Annie_wang 已提交
1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205
}
```

### getEntry

getEntry(): Entry

Obtains the KV pair from the current position.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type           | Description        |
| --------------- | ------------ |
| [Entry](#entry) | KV pair obtained.|

**Example**

```js
try {
    let resultSet;
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
1206
        console.info('getResultSet succeed.');
A
Annie_wang 已提交
1207
        resultSet = result;
A
Annie_wang 已提交
1208 1209
        const entry  = resultSet.getEntry();
        console.info("getEntry succeed:" + JSON.stringify(entry));
A
Annie_wang 已提交
1210
    }).catch((err) => {
A
Annie_wang 已提交
1211
        console.error('getResultSet failed: ' + err);
A
Annie_wang 已提交
1212 1213
    });
} catch (e) {
A
Annie_wang 已提交
1214
    console.error("getEntry failed: " + e);
A
Annie_wang 已提交
1215 1216 1217 1218 1219
}
```

## Query

A
Annie_wang 已提交
1220
Provides methods to create a **Query** object, which defines different data query criteria. A **Query** object supports a maximum of 256 predicates.
A
Annie_wang 已提交
1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

### constructor

constructor()

A constructor used to create a **Schema** instance.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

### reset

reset(): Query

Resets the **Query** object.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type          | Description                 |
| -------------- | --------------------- |
A
Annie_wang 已提交
1244
| [Query](#query) | **Query** object reset.|
A
Annie_wang 已提交
1245 1246 1247 1248 1249 1250 1251

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.equalTo("key", "value");
A
Annie_wang 已提交
1252
    console.info("query is " + query.getSqlLike());
A
Annie_wang 已提交
1253
    query.reset();
A
Annie_wang 已提交
1254
    console.info("query is " + query.getSqlLike());
A
Annie_wang 已提交
1255 1256
    query = null;
} catch (e) {
A
Annie_wang 已提交
1257
    console.error("simply calls should be ok :" + e);
A
Annie_wang 已提交
1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
}
```

### equalTo

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

Creates a **Query** object to match the specified field whose value is equal to the given value.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name | Type| Mandatory | Description                   |
| -----  | ------  | ----  | ----------------------- |
| fieId  | string  | Yes   |Field to match. It cannot contain '^'. |
| value  | number\|string\|boolean  | Yes   | Value specified.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1280
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1281 1282 1283 1284 1285 1286 1287

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.equalTo("field", "value");
A
Annie_wang 已提交
1288
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.ode is ${e.code},message is ${e.message}`);
}
```

### notEqualTo

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

Creates a **Query** object to match the specified field whose value is not equal to the specified value.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name | Type| Mandatory | Description                   |
| -----  | ------  | ----  | ----------------------- |
| fieId  | string  | Yes   |Field to match. It cannot contain '^'. |
| value  | number\|string\|boolean  | Yes   | Value specified.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1314
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1315 1316 1317 1318 1319 1320 1321

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.notEqualTo("field", "value");
A
Annie_wang 已提交
1322
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### greaterThan

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

Creates a **Query** object to match the specified field whose value is greater than the specified value.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**
| Name | Type| Mandatory | Description                   |
| -----  | ------  | ----  | ----------------------- |
| fieId  | string  | Yes   |Field to match. It cannot contain '^'. |
| value  | number\|string\|boolean  | Yes   | Value specified.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1347
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1348 1349 1350 1351 1352 1353 1354

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.greaterThan("field", "value");
A
Annie_wang 已提交
1355
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### lessThan

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

Creates a **Query** object to match the specified field whose value is less than the specified value.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**


| Name | Type| Mandatory | Description                   |
| -----  | ------  | ----  | ----------------------- |
| fieId  | string  | Yes   |Field to match. It cannot contain '^'. |
| value  | number\|string  | Yes   | Value specified.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1382
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1383 1384 1385 1386 1387 1388 1389

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.lessThan("field", "value");
A
Annie_wang 已提交
1390
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### greaterThanOrEqualTo

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

Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**


| Name | Type| Mandatory | Description                   |
| -----  | ------  | ----  | ----------------------- |
| fieId  | string  | Yes   |Field to match. It cannot contain '^'. |
| value  | number\|string  | Yes   | Value specified.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1417
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1418 1419 1420 1421 1422 1423 1424

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.greaterThanOrEqualTo("field", "value");
A
Annie_wang 已提交
1425
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### lessThanOrEqualTo

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

Creates a **Query** object to match the specified field whose value is less than or equal to the specified value.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**


| Name | Type| Mandatory | Description                   |
| -----  | ------  | ----  | ----------------------- |
| fieId  | string  | Yes   |Field to match. It cannot contain '^'. |
| value  | number\|string  | Yes   | Value specified.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1452
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1453 1454 1455 1456 1457 1458 1459

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.lessThanOrEqualTo("field", "value");
A
Annie_wang 已提交
1460
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### isNull

isNull(field: string): Query

Creates a **Query** object to match the specified field whose value is **null**.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                         |
| ------ | -------- | ---- | ----------------------------- |
| fieId  | string   | Yes  | Field to match. It cannot contain '^'.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1485
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1486 1487 1488 1489 1490 1491 1492

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.isNull("field");
A
Annie_wang 已提交
1493
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### inNumber

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

Creates a **Query** object to match the specified field whose value is within the specified list of numbers.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type| Mandatory| Description                         |
| --------- | -------- | ---- | ----------------------------- |
| fieId     | string   | Yes  | Field to match. It cannot contain '^'.|
| valueList | number[] | Yes  | List of numbers.           |

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1519
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1520 1521 1522 1523 1524 1525 1526

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.inNumber("field", [0, 1]);
A
Annie_wang 已提交
1527
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### inString

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

Creates a **Query** object to match the specified field whose value is within the specified list of strings.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type| Mandatory| Description                         |
| --------- | -------- | ---- | ----------------------------- |
| fieId     | string   | Yes  | Field to match. It cannot contain '^'.|
| valueList | string[] | Yes  | List of strings.     |

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1553
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1554 1555 1556 1557 1558 1559 1560

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.inString("field", ['test1', 'test2']);
A
Annie_wang 已提交
1561
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### notInNumber

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

Creates a **Query** object to match the specified field whose value is not within the specified list of numbers.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type| Mandatory| Description                         |
| --------- | -------- | ---- | ----------------------------- |
| fieId     | string   | Yes  | Field to match. It cannot contain '^'.|
| valueList | number[] | Yes  | List of numbers.           |

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1587
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1588 1589 1590 1591 1592 1593 1594

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.notInNumber("field", [0, 1]);
A
Annie_wang 已提交
1595
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### notInString

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

Creates a **Query** object to match the specified field whose value is not within the specified list of strings.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type| Mandatory| Description                         |
| --------- | -------- | ---- | ----------------------------- |
| fieId     | string   | Yes  | Field to match. It cannot contain '^'.|
| valueList | string[] | Yes  | List of strings.     |

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1621
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1622 1623 1624 1625 1626 1627 1628

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.notInString("field", ['test1', 'test2']);
A
Annie_wang 已提交
1629
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### like

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

Creates a **Query** object to match the specified field whose value is similar to the specified string.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                         |
| ------ | -------- | ---- | ----------------------------- |
| fieId  | string   | Yes  | Field to match. It cannot contain '^'.|
| value  | string   | Yes  | String specified.         |

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1655
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1656 1657 1658 1659 1660 1661 1662

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.like("field", "value");
A
Annie_wang 已提交
1663
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### unlike

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

Creates a **Query** object to match the specified field whose value is not similar to the specified string.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                         |
| ------ | -------- | ---- | ----------------------------- |
| fieId  | string   | Yes  | Field to match. It cannot contain '^'.|
| value  | string   | Yes  | String specified.         |

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1689
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1690 1691 1692 1693 1694 1695 1696

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.unlike("field", "value");
A
Annie_wang 已提交
1697
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### and

and(): Query

Creates a **Query** object with the AND condition.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type          | Description          |
| -------------- | -------------- |
A
Annie_wang 已提交
1716
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1717 1718 1719 1720 1721 1722 1723 1724 1725

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.notEqualTo("field", "value1");
    query.and();
    query.notEqualTo("field", "value2");
A
Annie_wang 已提交
1726
    console.info("query is " + query.getSqlLike());
A
Annie_wang 已提交
1727 1728
    query = null;
} catch (e) {
A
Annie_wang 已提交
1729
    console.error("duplicated calls should be ok :" + e);
A
Annie_wang 已提交
1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744
}
```

### or

or(): Query

Creates a **Query** object with the OR condition.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type          | Description          |
| -------------- | -------------- |
A
Annie_wang 已提交
1745
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1746 1747 1748 1749 1750 1751 1752 1753 1754

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.notEqualTo("field", "value1");
    query.or();
    query.notEqualTo("field", "value2");
A
Annie_wang 已提交
1755
    console.info("query is " + query.getSqlLike());
A
Annie_wang 已提交
1756 1757
    query = null;
} catch (e) {
A
Annie_wang 已提交
1758
    console.error("duplicated calls should be ok :" + e);
A
Annie_wang 已提交
1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779
}
```

### orderByAsc

orderByAsc(field: string): Query

Creates a **Query** object to sort the query results in ascending order.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                         |
| ------ | -------- | ---- | ----------------------------- |
| fieId  | string   | Yes  | Field to match. It cannot contain '^'.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1780
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1781 1782 1783 1784 1785 1786 1787 1788

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.notEqualTo("field", "value");
    query.orderByAsc("field");
A
Annie_wang 已提交
1789
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### orderByDesc

orderByDesc(field: string): Query

Creates a **Query** object to sort the query results in descending order.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                         |
| ------ | -------- | ---- | ----------------------------- |
| fieId  | string   | Yes  | Field to match. It cannot contain '^'.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1814
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1815 1816 1817 1818 1819 1820 1821 1822

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.notEqualTo("field", "value");
    query.orderByDesc("field");
A
Annie_wang 已提交
1823
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1824 1825 1826 1827 1828 1829 1830 1831 1832 1833
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### limit

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

A
Annie_wang 已提交
1834
Creates a **Query** object to specify the number of records of the query result and where to start. This API must be called after the invocation of the **orderByAsc()**, **orderByDesc()**, and the query APIs of the **Query** object.
A
Annie_wang 已提交
1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description              |
| ------ | -------- | ---- | ------------------ |
| total  | number   | Yes  | Number of results to query.|
| offset | number   | Yes  | Start position for query.    |

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1849
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1850 1851 1852 1853 1854 1855 1856 1857 1858 1859

**Example**

```js
let total = 10;
let offset = 1;
try {
    let query = new distributedKVStore.Query();
    query.notEqualTo("field", "value");
    query.limit(total, offset);
A
Annie_wang 已提交
1860
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884
    query = null;
} catch (e) {
     console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### isNotNull

isNotNull(field: string): Query

Creates a **Query** object to match the specified field whose value is not **null**.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                         |
| ------ | -------- | ---- | ----------------------------- |
| fieId  | string   | Yes  | Field to match. It cannot contain '^'.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1885
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1886 1887 1888 1889 1890 1891 1892

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.isNotNull("field");
A
Annie_wang 已提交
1893
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### beginGroup

beginGroup(): Query

Creates a **Query** object for a query condition group with a left parenthesis.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1912
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1913 1914 1915 1916 1917 1918 1919 1920 1921

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.beginGroup();
    query.isNotNull("field");
    query.endGroup();
A
Annie_wang 已提交
1922
    console.info("query is " + query.getSqlLike());
A
Annie_wang 已提交
1923 1924
    query = null;
} catch (e) {
A
Annie_wang 已提交
1925
    console.error("duplicated calls should be ok :" + e);
A
Annie_wang 已提交
1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940
}
```

### endGroup

endGroup(): Query

Creates a **Query** object for a query condition group with a right parenthesis.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1941
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1942 1943 1944 1945 1946 1947 1948 1949 1950

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.beginGroup();
    query.isNotNull("field");
    query.endGroup();
A
Annie_wang 已提交
1951
    console.info("query is " + query.getSqlLike());
A
Annie_wang 已提交
1952 1953
    query = null;
} catch (e) {
A
Annie_wang 已提交
1954
    console.error("duplicated calls should be ok :" + e);
A
Annie_wang 已提交
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975
}
```

### prefixKey

prefixKey(prefix: string): Query

Creates a **Query** object with a specified key prefix.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description              |
| ------ | -------- | ---- | ------------------ |
| prefix | string   | Yes  | Key prefix.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
1976
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
1977 1978 1979 1980 1981 1982 1983 1984

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.prefixKey("$.name");
    query.prefixKey("0");
A
Annie_wang 已提交
1985
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### setSuggestIndex

setSuggestIndex(index: string): Query

Creates a **Query** object with an index preferentially used for query.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description              |
| ------ | -------- | ---- | ------------------ |
| index  | string   | Yes  | Index preferentially used for query.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
2010
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
2011 2012 2013 2014 2015 2016 2017 2018

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.setSuggestIndex("$.name");
    query.setSuggestIndex("0");
A
Annie_wang 已提交
2019
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030
    query = null;
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### deviceId

deviceId(deviceId:string):Query

Creates a **Query** object with the device ID as the key prefix.
A
Annie_wang 已提交
2031
> **NOTE**
A
Annie_wang 已提交
2032 2033 2034
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type| Mandatory| Description              |
| -------- | -------- | ---- | ------------------ |
| deviceId | string   | Yes  | Device ID.|

**Return value**

| Type          | Description           |
| -------------- | --------------- |
A
Annie_wang 已提交
2048
| [Query](#query) | **Query** object created.|
A
Annie_wang 已提交
2049 2050 2051 2052 2053 2054 2055

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    query.deviceId("deviceId");
A
Annie_wang 已提交
2056
    console.info(`query is ${query.getSqlLike()}`);
A
Annie_wang 已提交
2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081
} catch (e) {
    console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`);
}
```

### getSqlLike

getSqlLike():string

Obtains the query statement of the **Query** object.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type  | Description                                |
| ------ | ------------------------------------ |
| string | Returns the query statement obtained.|

**Example**

```js
try {
    let query = new distributedKVStore.Query();
    let sql1 = query.getSqlLike();
A
Annie_wang 已提交
2082
    console.info(`GetSqlLike sql= ${sql1}`);
A
Annie_wang 已提交
2083
} catch (e) {
A
Annie_wang 已提交
2084
    console.error("duplicated calls should be ok : " + e);
A
Annie_wang 已提交
2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113
}
```

## SingleKVStore

Implements data management in a single KV store, such as adding data, deleting data, and subscribing to data changes or data synchronization completion.

Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance.

### put

put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback&lt;void&gt;): void

Adds a KV pair of the specified type to this KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name | Type| Mandatory | Description                   |
| -----  | ------  | ----  | ----------------------- |
| key    | string  | Yes   |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).  |
| value  | Uint8Array \| string \| number \| boolean | Yes   |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants).  |
| callback | AsyncCallback&lt;void&gt; | Yes   |Callback invoked to return the result.  |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2114 2115 2116 2117 2118 2119 2120 2121 2122 2123
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100003     | Database corrupted.                      |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
2124 2125 2126 2127 2128 2129 2130 2131 2132

**Example**

```js
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, function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
2133
            console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2134 2135
            return;
        }
A
Annie_wang 已提交
2136
        console.info("Succeeded in putting");
A
Annie_wang 已提交
2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### put

put(key: string, value: Uint8Array | string | number | boolean): Promise&lt;void&gt;

Adds a KV pair of the specified type to this KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name | Type| Mandatory | Description                   |
| -----  | ------  | ----  | ----------------------- |
| key    | string  | Yes   |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).  |
| value  | Uint8Array \| string \| number \| boolean | Yes   |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants).  |

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2168 2169 2170 2171 2172 2173 2174 2175 2176 2177
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100003     | Database corrupted.                      |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
2178 2179 2180 2181 2182 2183 2184 2185

**Example**

```js
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((data) => {
A
Annie_wang 已提交
2186
        console.info(`Succeeded in putting.data=${data}`);
A
Annie_wang 已提交
2187
    }).catch((err) => {
A
Annie_wang 已提交
2188
        console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### putBatch

putBatch(entries: Entry[], callback: AsyncCallback&lt;void&gt;): void

Batch inserts KV pairs to this single KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                | Mandatory| Description                    |
| -------- | ------------------------ | ---- | ------------------------ |
A
Annie_wang 已提交
2207
| entries  | [Entry](#entry)[]        | Yes  | KV pairs to insert in batches. An **entries** object allows a maximum of 128 entries.|
A
Annie_wang 已提交
2208 2209 2210 2211 2212 2213
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.              |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2214 2215 2216 2217 2218 2219 2220 2221 2222 2223
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100003     | Database corrupted.                      |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
2241
    console.info(`entries: ${entries}`);
A
Annie_wang 已提交
2242 2243
    kvStore.putBatch(entries, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
2244
            console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2245 2246
            return;
        }
A
Annie_wang 已提交
2247
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
2248 2249
        kvStore.getEntries('batch_test_string_key', function (err, entries) {
            if (err != undefined) {
A
Annie_wang 已提交
2250
                console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2251
            }
A
Annie_wang 已提交
2252 2253 2254
            console.info('Succeeded in getting Entries');
            console.info(`entries.length: ${entries.length}`);
            console.info(`entries[0]: ${entries[0]}`);
A
Annie_wang 已提交
2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273
        });
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `);
}
```

### putBatch

putBatch(entries: Entry[]): Promise&lt;void&gt;

Batch inserts KV pairs to this single KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name | Type         | Mandatory| Description                    |
| ------- | ----------------- | ---- | ------------------------ |
A
Annie_wang 已提交
2274
| entries | [Entry](#entry)[] | Yes  | KV pairs to insert in batches. An **entries** object allows a maximum of 128 entries.|
A
Annie_wang 已提交
2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2286 2287 2288 2289 2290 2291 2292 2293 2294 2295
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100003     | Database corrupted.                      |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
2313
    console.info(`entries: ${entries}`);
A
Annie_wang 已提交
2314
    kvStore.putBatch(entries).then(async (entries) => {
A
Annie_wang 已提交
2315
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
2316
        kvStore.getEntries('batch_test_string_key').then((entries) => {
A
Annie_wang 已提交
2317 2318
            console.info('Succeeded in getting Entries');
            console.info(`PutBatch ${entries}`);
A
Annie_wang 已提交
2319
        }).catch((err) => {
A
Annie_wang 已提交
2320
            console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2321 2322
        });
    }).catch((err) => {
A
Annie_wang 已提交
2323
        console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `);
}
```

### putBatch

putBatch(value: Array&lt;ValuesBucket&gt;, callback: AsyncCallback&lt;void&gt;): void

Writes data to this single KV store. This API uses an asynchronous callback to return the result.

**System API**: This is a system API.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                                                    | Mandatory| Description              |
| -------- | ------------------------------------------------------------ | ---- | ------------------ |
A
Annie_wang 已提交
2344
| value    | Array&lt;[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)&gt; | Yes  | Data to write.|
A
Annie_wang 已提交
2345 2346 2347 2348 2349 2350
| callback | AsyncCallback&lt;void&gt;                                     | Yes  | Callback invoked to return the result.        |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2351 2352 2353 2354 2355 2356 2357 2358 2359 2360
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100003     | Database corrupted.                      |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376

**Example**

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

    v8Arr.push(vb1);
    v8Arr.push(vb2);
    v8Arr.push(vb3);
    kvStore.putBatch(v8Arr, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
2377
            console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2378 2379
            return;
        }
A
Annie_wang 已提交
2380
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
2381 2382
    })
} catch (e) {
A
Annie_wang 已提交
2383
    console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400
}
```

### putBatch

putBatch(value: Array&lt;ValuesBucket&gt;): Promise&lt;void&gt;

Write data to this KV store. This API uses a promise to return the result.

**System API**: This is a system API.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type                                                    | Mandatory| Description              |
| ------ | ------------------------------------------------------------ | ---- | ------------------ |
A
Annie_wang 已提交
2401
| value  | Array&lt;[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)&gt; | Yes  | Data to write. |
A
Annie_wang 已提交
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2413 2414 2415 2416 2417 2418 2419 2420 2421 2422
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100003     | Database corrupted.                      |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437

**Example**

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

    v8Arr.push(vb1);
    v8Arr.push(vb2);
    v8Arr.push(vb3);
    kvStore.putBatch(v8Arr).then(async (data) => {
A
Annie_wang 已提交
2438
        console.info(`Succeeded in putting patch`);
A
Annie_wang 已提交
2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465
    }).catch((err) => {
        console.error(`putBatch fail.code is ${err.code},message is ${err.message}`);
    });
} catch (e) {
    console.error(`putBatch fail.code is ${e.code},message is ${e.message}`);
}
```

### delete

delete(key: string, callback: AsyncCallback&lt;void&gt;): void

Deletes a KV pair from this KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                 | Mandatory| Description                                                        |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| key      | string                    | Yes  | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).|
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.                                                  |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2466
| ID| **Error Message**                          |
A
Annie_wang 已提交
2467 2468 2469 2470
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005    | Database or result set already closed. |

A
Annie_wang 已提交
2471 2472 2473 2474 2475 2476
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |

A
Annie_wang 已提交
2477 2478 2479 2480 2481 2482 2483 2484
**Example**

```js
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, function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
2485
            console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2486 2487
            return;
        }
A
Annie_wang 已提交
2488
        console.info('Succeeded in putting');
A
Annie_wang 已提交
2489 2490
        kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
2491
                console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2492 2493
                return;
            }
A
Annie_wang 已提交
2494
            console.info('Succeeded in deleting');
A
Annie_wang 已提交
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525
        });
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### delete

delete(key: string): Promise&lt;void&gt;

Deletes a KV pair from this KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                                                        |
| ------ | -------- | ---- | ------------------------------------------------------------ |
| key    | string   | Yes  | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).|

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2526 2527 2528 2529 2530 2531 2532 2533 2534 2535
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100003     | Database corrupted.                      |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
2536 2537 2538 2539 2540 2541 2542 2543

**Example**

```js
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((data) => {
A
Annie_wang 已提交
2544
        console.info(`Succeeded in putting: ${data}`);
A
Annie_wang 已提交
2545
        kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => {
A
Annie_wang 已提交
2546
            console.info('Succeeded in deleting');
A
Annie_wang 已提交
2547
        }).catch((err) => {
A
Annie_wang 已提交
2548
            console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2549 2550
        });
    }).catch((err) => {
A
Annie_wang 已提交
2551
        console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### delete

delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;void&gt;)

Deletes KV pairs from this KV store. This API uses an asynchronous callback to return the result.

**System API**: This is a system API.

**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider

**Parameters**

| Name    | Type                                                    | Mandatory| Description                                           |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- |
A
Annie_wang 已提交
2572
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes  | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.|
A
Annie_wang 已提交
2573 2574 2575 2576 2577 2578
| callback   | AsyncCallback&lt;void&gt;                                    | Yes  | Callback invoked to return the result.                                     |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2579
| ID| **Error Message**                          |
A
Annie_wang 已提交
2580 2581 2582 2583
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005    | Database or result set already closed. |

A
Annie_wang 已提交
2584 2585 2586 2587 2588 2589
For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |

A
Annie_wang 已提交
2590 2591 2592 2593 2594 2595
**Example**

```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';
try {
    let predicates = new dataSharePredicates.DataSharePredicates();
A
Annie_wang 已提交
2596 2597 2598 2599 2600 2601
    let arr = ["name"];
    predicates.inKeys(arr);
    kvStore.put("name", "bob", function (err, data) {
        if (err != undefined) {
            console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
            return;
A
Annie_wang 已提交
2602
        }
A
Annie_wang 已提交
2603 2604 2605 2606 2607 2608 2609 2610
        console.info("Succeeded in putting");
        kvStore.delete(predicates, function (err, data) {
            if (err == undefined) {
                console.info('Succeeded in deleting');
            } else {
                console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
            }
        });
A
Annie_wang 已提交
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### delete

delete(predicates: dataSharePredicates.DataSharePredicates): Promise&lt;void&gt;

Deletes KV pairs from this KV store. This API uses a promise to return the result.

**System API**: This is a system API.

**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider

**Parameters**

| Name    | Type                                                    | Mandatory| Description                                           |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes  | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.|

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2643 2644 2645 2646 2647 2648 2649 2650 2651 2652
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100003     | Database corrupted.                      |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663

**Example**

```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';

try {
    let predicates = new dataSharePredicates.DataSharePredicates();
    let arr = ["name"];
    predicates.inKeys(arr);
    kvStore.put("name", "bob").then((data) => {
A
Annie_wang 已提交
2664
        console.info(`Succeeded in putting: ${data}`);
A
Annie_wang 已提交
2665
        kvStore.delete(predicates).then((data) => {
A
Annie_wang 已提交
2666
            console.info('Succeeded in deleting');
A
Annie_wang 已提交
2667
        }).catch((err) => {
A
Annie_wang 已提交
2668
            console.error(`Failed to delete.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2669 2670
        });
    }).catch((err) => {
A
Annie_wang 已提交
2671
        console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### deleteBatch

deleteBatch(keys: string[], callback: AsyncCallback&lt;void&gt;): void

Batch deletes KV pairs from this single KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                 | Mandatory| Description                    |
| -------- | ------------------------- | ---- | ------------------------ |
| keys     | string[]                  | Yes  | KV pairs to delete in batches.|
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.              |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2697 2698 2699 2700 2701 2702 2703 2704 2705 2706
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100003     | Database corrupted.                      |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725

**Example**

```js
try {
    let entries = [];
    let keys = [];
    for (var i = 0; i < 5; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
        keys.push(key + i);
    }
A
Annie_wang 已提交
2726
    console.info(`entries: ${entries}`);
A
Annie_wang 已提交
2727 2728
    kvStore.putBatch(entries, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
2729
            console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2730 2731
            return;
        }
A
Annie_wang 已提交
2732
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
2733 2734
        kvStore.deleteBatch(keys, async function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
2735
                console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2736 2737
                return;
            }
A
Annie_wang 已提交
2738
            console.info('Succeeded in deleting Batch');
A
Annie_wang 已提交
2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769
        });
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### deleteBatch

deleteBatch(keys: string[]): Promise&lt;void&gt;

Batch deletes KV pairs from this single KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                    |
| ------ | -------- | ---- | ------------------------ |
| keys   | string[] | Yes  | KV pairs to delete in batches.|

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2770 2771 2772 2773 2774 2775 2776 2777 2778 2779
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100003     | Database corrupted.                      |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798

**Example**

```js
try {
    let entries = [];
    let keys = [];
    for (var i = 0; i < 5; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
        keys.push(key + i);
    }
A
Annie_wang 已提交
2799
    console.info(`entries: ${entries}`);
A
Annie_wang 已提交
2800
    kvStore.putBatch(entries).then(async (data) => {
A
Annie_wang 已提交
2801
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
2802
        kvStore.deleteBatch(keys).then((err) => {
A
Annie_wang 已提交
2803
            console.info('Succeeded in deleting Batch');
A
Annie_wang 已提交
2804
        }).catch((err) => {
A
Annie_wang 已提交
2805
            console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2806 2807
        });
    }).catch((err) => {
A
Annie_wang 已提交
2808
        console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2809 2810
    });
} catch (e) {
J
Jiefeng Li 已提交
2811
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
2812 2813 2814 2815 2816 2817 2818 2819
}
```

### removeDeviceData

removeDeviceData(deviceId: string, callback: AsyncCallback&lt;void&gt;): void

Deletes data of a device. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
2820
> **NOTE**
A
Annie_wang 已提交
2821 2822 2823
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name  | Type                 | Mandatory| Description                  |
| -------- | ------------------------- | ---- | ---------------------- |
| deviceId | string                    | Yes  | ID of the target device.|
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.            |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2838
| ID| **Error Message**                          |
A
Annie_wang 已提交
2839 2840 2841 2842 2843 2844 2845 2846 2847 2848
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
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 function (err, data) {
A
Annie_wang 已提交
2849
        console.info('Succeeded in putting data');
A
Annie_wang 已提交
2850 2851 2852
        const deviceid = 'no_exist_device_id';
        kvStore.removeDeviceData(deviceid, async function (err, data) {
            if (err == undefined) {
A
Annie_wang 已提交
2853
                console.info('succeeded in removing device data');
A
Annie_wang 已提交
2854
            } else {
A
Annie_wang 已提交
2855
                console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `);
A
Annie_wang 已提交
2856
                kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err, data) {
A
Annie_wang 已提交
2857
                    console.info('Succeeded in getting data');
A
Annie_wang 已提交
2858 2859 2860 2861 2862
                });
            }
        });
    });
} catch (e) {
J
Jiefeng Li 已提交
2863
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`)
A
Annie_wang 已提交
2864 2865 2866 2867 2868 2869 2870 2871
}
```

### removeDeviceData

removeDeviceData(deviceId: string): Promise&lt;void&gt;

Deletes data of a device. This API uses a promise to return the result.
A
Annie_wang 已提交
2872
> **NOTE**
A
Annie_wang 已提交
2873 2874 2875
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name  | Type| Mandatory| Description                  |
| -------- | -------- | ---- | ---------------------- |
| deviceId | string   | Yes  | ID of the target device.|

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2895
| ID| **Error Message**                          |
A
Annie_wang 已提交
2896 2897 2898 2899 2900 2901 2902 2903 2904 2905
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
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((err) => {
A
Annie_wang 已提交
2906
        console.info('Succeeded in putting data');
A
Annie_wang 已提交
2907
    }).catch((err) => {
A
Annie_wang 已提交
2908
        console.error(`Failed to put data.code is ${err.code},message is ${err.message} `);
A
Annie_wang 已提交
2909 2910 2911
    });
    const deviceid = 'no_exist_device_id';
    kvStore.removeDeviceData(deviceid).then((err) => {
A
Annie_wang 已提交
2912
        console.info('succeeded in removing device data');
A
Annie_wang 已提交
2913
    }).catch((err) => {
A
Annie_wang 已提交
2914
        console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `);
A
Annie_wang 已提交
2915 2916
    });
    kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
A
Annie_wang 已提交
2917
        console.info('Succeeded in getting data');
A
Annie_wang 已提交
2918
    }).catch((err) => {
A
Annie_wang 已提交
2919
        console.error(`Failed to get data.code is ${err.code},message is ${err.message} `);
A
Annie_wang 已提交
2920 2921
    });
} catch (e) {
J
Jiefeng Li 已提交
2922
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`)
A
Annie_wang 已提交
2923 2924 2925 2926 2927
}
```

### get

A
Annie_wang 已提交
2928
get(key: string, callback: AsyncCallback&lt;boolean | string | number | Uint8Array&gt;): void
A
Annie_wang 已提交
2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944

Obtains the value of the specified key. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name | Type| Mandatory | Description                   |
| -----  | ------  | ----  | ----------------------- |
| key    |string   | Yes   |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). |
| callback  |AsyncCallback&lt;boolean \| string \| number \| Uint8Array&gt; | Yes   |Callback invoked to return the value obtained. |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
2945
| ID| **Error Message**                          |
A
Annie_wang 已提交
2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100004     | Not found.                             |
| 15100005     | Database or result set already closed. |

**Example**

```js
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, function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
2959
            console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2960 2961
            return;
        }
A
Annie_wang 已提交
2962
        console.info("Succeeded in putting");
A
Annie_wang 已提交
2963 2964
        kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
2965
                console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
2966 2967
                return;
            }
A
Annie_wang 已提交
2968
            console.info(`Succeeded in getting data.data=${data}`);
A
Annie_wang 已提交
2969 2970 2971
        });
    });
} catch (e) {
A
Annie_wang 已提交
2972
    console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
2973 2974 2975 2976 2977
}
```

### get

A
Annie_wang 已提交
2978
get(key: string): Promise&lt;boolean | string | number | Uint8Array&gt;
A
Annie_wang 已提交
2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999

Obtains the value of the specified key. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                                                        |
| ------ | -------- | ---- | ------------------------------------------------------------ |
| key    | string   | Yes  | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).|

**Return value**

| Type   | Description      |
| ------  | -------   |
|Promise&lt;Uint8Array \| string \| boolean \| number&gt; |Promise used to return the value obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3000
| ID| **Error Message**                          |
A
Annie_wang 已提交
3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100004     | Not found.                             |
| 15100005     | Database or result set already closed. |

**Example**

```js
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((data) => {
A
Annie_wang 已提交
3013
        console.info(`Succeeded in putting data.data=${data}`);
A
Annie_wang 已提交
3014
        kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
A
Annie_wang 已提交
3015
            console.info(`Succeeded in getting data.data=${data}`);
A
Annie_wang 已提交
3016
        }).catch((err) => {
A
Annie_wang 已提交
3017
            console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3018 3019
        });
    }).catch((err) => {
A
Annie_wang 已提交
3020
        console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3021 3022
    });
} catch (e) {
A
Annie_wang 已提交
3023
    console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
}
```

### getEntries

getEntries(keyPrefix: string, callback: AsyncCallback&lt;Entry[]&gt;): void

Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type                              | Mandatory| Description                                    |
| --------- | -------------------------------------- | ---- | ---------------------------------------- |
| keyPrefix | string                                 | Yes  | Key prefix to match.                    |
A
Annie_wang 已提交
3040
| callback  | AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes  | Callback invoked to return the KV pairs that match the specified prefix.|
A
Annie_wang 已提交
3041 3042 3043 3044 3045

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3046
| ID| **Error Message**                          |
A
Annie_wang 已提交
3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
3067
    console.info(`entries: ${entries}`);
A
Annie_wang 已提交
3068 3069
    kvStore.putBatch(entries, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
3070
            console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3071 3072
            return;
        }
A
Annie_wang 已提交
3073
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
3074 3075
        kvStore.getEntries('batch_test_string_key', function (err, entries) {
            if (err != undefined) {
A
Annie_wang 已提交
3076
                console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3077 3078
                return;
            }
A
Annie_wang 已提交
3079 3080 3081
            console.info('Succeeded in getting Entries');
            console.info(`entries.length: ${entries.length}`);
            console.info(`entries[0]: ${entries[0]}`);
A
Annie_wang 已提交
3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106
        });
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `);
}
```

### getEntries

getEntries(keyPrefix: string): Promise&lt;Entry[]&gt;

Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type| Mandatory| Description                |
| --------- | -------- | ---- | -------------------- |
| keyPrefix | string   | Yes  | Key prefix to match.|

**Return value**

| Type                            | Description                                       |
| -------------------------------- | ------------------------------------------- |
A
Annie_wang 已提交
3107
| Promise&lt;[Entry](#entry)[]&gt; | Promise used to return the KV pairs that match the specified prefix.|
A
Annie_wang 已提交
3108 3109 3110 3111 3112

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3113
| ID| **Error Message**                          |
A
Annie_wang 已提交
3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
3134
    console.info(`entries: ${entries}`);
A
Annie_wang 已提交
3135
    kvStore.putBatch(entries).then(async (entries) => {
A
Annie_wang 已提交
3136
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
3137
        kvStore.getEntries('batch_test_string_key').then((entries) => {
A
Annie_wang 已提交
3138 3139
            console.info('Succeeded in getting Entries');
            console.info(`PutBatch ${entries}`);
A
Annie_wang 已提交
3140
        }).catch((err) => {
A
Annie_wang 已提交
3141
            console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3142 3143
        });
    }).catch((err) => {
A
Annie_wang 已提交
3144
        console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `);
}
```

### getEntries

getEntries(query: Query, callback: AsyncCallback&lt;Entry[]&gt;): void

Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                              | Mandatory| Description                                           |
| -------- | -------------------------------------- | ---- | ----------------------------------------------- |
A
Annie_wang 已提交
3163
| query    | [Query](#query)                         | Yes  | Key prefix to match.                           |
A
Annie_wang 已提交
3164
| callback | AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes  | Callback invoked to return the KV pairs that match the specified **Query** object.|
A
Annie_wang 已提交
3165 3166 3167 3168 3169

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3170
| ID| **Error Message**                          |
A
Annie_wang 已提交
3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    var arr = new Uint8Array([21, 31]);
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_bool_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.BYTE_ARRAY,
                value: arr
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
3192
    console.info(`entries: {entries}`);
A
Annie_wang 已提交
3193
    kvStore.putBatch(entries, async function (err, data) {
A
Annie_wang 已提交
3194
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
3195 3196 3197 3198
        const query = new distributedKVStore.Query();
        query.prefixKey("batch_test");
        kvStore.getEntries(query, function (err, entries) {
            if (err != undefined) {
A
Annie_wang 已提交
3199
                console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3200 3201
                return;
            }
A
Annie_wang 已提交
3202 3203 3204
            console.info('Succeeded in getting Entries');
            console.info(`entries.length: ${entries.length}`);
            console.info(`entries[0]: ${entries[0]}`);
A
Annie_wang 已提交
3205 3206 3207
        });
    });
} catch (e) {
A
Annie_wang 已提交
3208
    console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223
}
```

### getEntries

getEntries(query: Query): Promise&lt;Entry[]&gt;

Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type      | Mandatory| Description          |
| ------ | -------------- | ---- | -------------- |
A
Annie_wang 已提交
3224
| query  | [Query](#query) | Yes  | **Query** object to match.|
A
Annie_wang 已提交
3225 3226 3227 3228 3229

**Return value**

| Type                            | Description                                              |
| -------------------------------- | -------------------------------------------------- |
A
Annie_wang 已提交
3230
| Promise&lt;[Entry](#entry)[]&gt; | Promise used to return the KV pairs that match the specified **Query** object.|
A
Annie_wang 已提交
3231 3232 3233 3234 3235

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3236
| ID| **Error Message**                          |
A
Annie_wang 已提交
3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    var arr = new Uint8Array([21, 31]);
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_bool_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.BYTE_ARRAY,
                value: arr
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
3258
    console.info(`entries: {entries}`);
A
Annie_wang 已提交
3259
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
3260
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
3261 3262 3263
        const query = new distributedKVStore.Query();
        query.prefixKey("batch_test");
        kvStore.getEntries(query).then((entries) => {
A
Annie_wang 已提交
3264
            console.info('Succeeded in getting Entries');
A
Annie_wang 已提交
3265
        }).catch((err) => {
A
Annie_wang 已提交
3266
            console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3267 3268
        });
    }).catch((err) => {
A
Annie_wang 已提交
3269
        console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`)
A
Annie_wang 已提交
3270
    });
A
Annie_wang 已提交
3271
    console.info('Succeeded in getting Entries');
A
Annie_wang 已提交
3272
} catch (e) {
A
Annie_wang 已提交
3273
    console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289
}
```

### getResultSet

getResultSet(keyPrefix: string, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void

Obtains a result set with the specified prefix from this single KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type                                                  | Mandatory| Description                                |
| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ |
| keyPrefix | string                                                     | Yes  | Key prefix to match.                |
A
Annie_wang 已提交
3290
| callback  | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes  | Callback invoked to return the result set with the specified prefix.|
A
Annie_wang 已提交
3291 3292 3293 3294 3295

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3296
| ID| **Error Message**                          |
A
Annie_wang 已提交
3297
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
3298
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
3299 3300 3301
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

A
Annie_wang 已提交
3302

A
Annie_wang 已提交
3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321
**Example**

```js
try {
    let resultSet;
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
3322
            console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3323 3324
            return;
        }
A
Annie_wang 已提交
3325
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
3326 3327
        kvStore.getResultSet('batch_test_string_key', async function (err, result) {
            if (err != undefined) {
A
Annie_wang 已提交
3328
                console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3329 3330
                return;
            }
A
Annie_wang 已提交
3331
            console.info('Succeeded in getting result set');
A
Annie_wang 已提交
3332 3333 3334
            resultSet = result;
            kvStore.closeResultSet(resultSet, function (err, data) {
                if (err != undefined) {
A
Annie_wang 已提交
3335
                    console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3336 3337
                    return;
                }
A
Annie_wang 已提交
3338
                console.info('Succeeded in closing result set');
A
Annie_wang 已提交
3339 3340 3341 3342
            })
        });
    });
} catch (e) {
J
Jiefeng Li 已提交
3343
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364
}
```

### getResultSet

getResultSet(keyPrefix: string): Promise&lt;KVStoreResultSet&gt;

Obtains a result set with the specified prefix from this single KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type| Mandatory| Description                |
| --------- | -------- | ---- | -------------------- |
| keyPrefix | string   | Yes  | Key prefix to match.|

**Return value**

| Type                                                | Description                                   |
| ---------------------------------------------------- | --------------------------------------- |
A
Annie_wang 已提交
3365
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise used to return the result set with the specified prefix.|
A
Annie_wang 已提交
3366 3367 3368 3369 3370

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3371
| ID| **Error Message**                          |
A
Annie_wang 已提交
3372
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
3373
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let resultSet;
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
3395
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
3396
    }).catch((err) => {
A
Annie_wang 已提交
3397
        console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3398 3399
    });
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
3400
        console.info('Succeeded in getting result set');
A
Annie_wang 已提交
3401 3402
        resultSet = result;
    }).catch((err) => {
A
Annie_wang 已提交
3403
        console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3404 3405
    });
    kvStore.closeResultSet(resultSet).then((err) => {
A
Annie_wang 已提交
3406
        console.info('Succeeded in closing result set');
A
Annie_wang 已提交
3407
    }).catch((err) => {
A
Annie_wang 已提交
3408
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3409 3410
    });
} catch (e) {
J
Jiefeng Li 已提交
3411
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433
}
```

### getResultSet

getResultSet(query: Query, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void

Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                                                  | Mandatory| Description                                                     |
| -------- | ---------------------------------------------------------- | ---- | --------------------------------------------------------- |
| query    | Query                                                      | Yes  | **Query** object to match.                                           |
| callback | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes  | Callback invoked to return the **KVStoreResultSet** object obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3434
| ID| **Error Message**                          |
A
Annie_wang 已提交
3435
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
3436
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let resultSet;
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
3459
            console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3460 3461
            return;
        }
A
Annie_wang 已提交
3462
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
3463 3464 3465 3466
        const query = new distributedKVStore.Query();
        query.prefixKey("batch_test");
        kvStore.getResultSet(query, async function (err, result) {
            if (err != undefined) {
A
Annie_wang 已提交
3467
                console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3468 3469
                return;
            }
A
Annie_wang 已提交
3470
            console.info('Succeeded in getting result set');
A
Annie_wang 已提交
3471 3472 3473
        });
    });
} catch (e) {
J
Jiefeng Li 已提交
3474
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489
}
```

### getResultSet

getResultSet(query: Query): Promise&lt;KVStoreResultSet&gt;

Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type      | Mandatory| Description          |
| ------ | -------------- | ---- | -------------- |
A
Annie_wang 已提交
3490
| query  | [Query](#query) | Yes  | **Query** object to match.|
A
Annie_wang 已提交
3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501

**Return value**

| Type                                                | Description                                                        |
| ---------------------------------------------------- | ------------------------------------------------------------ |
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise used to return the **KVStoreResultSet** object obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3502
| ID| **Error Message**                          |
A
Annie_wang 已提交
3503
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
3504
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let resultSet;
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
3526
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
3527
    }).catch((err) => {
A
Annie_wang 已提交
3528
        console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3529 3530 3531 3532
    });
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    kvStore.getResultSet(query).then((result) => {
A
Annie_wang 已提交
3533
        console.info('Succeeded in getting result set');
A
Annie_wang 已提交
3534 3535
        resultSet = result;
    }).catch((err) => {
A
Annie_wang 已提交
3536
        console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3537 3538
    });
} catch (e) {
J
Jiefeng Li 已提交
3539
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563
}    
```

### getResultSet

getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void

Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses an asynchronous callback to return the result.

**System API**: This is a system API.

**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider

**Parameters**

| Name    | Type                                                    | Mandatory| Description                                                        |
| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes  | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.             |
| callback   | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt;   | Yes  | Callback invoked to return the **KVStoreResultSet** object obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3564
| ID| **Error Message**                          |
A
Annie_wang 已提交
3565
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
3566
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';

try {
    let resultSet;
    let predicates = new dataSharePredicates.DataSharePredicates();
    predicates.prefixKey("batch_test_string_key");
    kvStore.getResultSet(predicates, async function (err, result) {
        if (err != undefined) {
A
Annie_wang 已提交
3581
            console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3582 3583
            return;
        }
A
Annie_wang 已提交
3584
        console.info('Succeeded in getting result set');
A
Annie_wang 已提交
3585 3586 3587
        resultSet = result;
        kvStore.closeResultSet(resultSet, function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
3588
                console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3589 3590
                return;
            }
A
Annie_wang 已提交
3591
            console.info('Succeeded in closing result set');
A
Annie_wang 已提交
3592 3593 3594
        })
    });
} catch (e) {
J
Jiefeng Li 已提交
3595
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624
}
```

### getResultSet

getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise&lt;KVStoreResultSet&gt;

Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses a promise to return the result.

**System API**: This is a system API.

**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider

**Parameters**

| Name    | Type                                                    | Mandatory| Description                                           |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes  | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.|

**Return value**

| Type                                                | Description                     |
| ---------------------------------------------------- | ------------------------- |
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3625
| ID| **Error Message**                          |
A
Annie_wang 已提交
3626
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
3627
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';

try {
    let resultSet;
    let predicates = new dataSharePredicates.DataSharePredicates();
    predicates.prefixKey("batch_test_string_key");
    kvStore.getResultSet(predicates).then((result) => {
A
Annie_wang 已提交
3641
        console.info('Succeeded in getting result set');
A
Annie_wang 已提交
3642 3643
        resultSet = result;
    }).catch((err) => {
A
Annie_wang 已提交
3644
        console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3645 3646
    });
    kvStore.closeResultSet(resultSet).then((err) => {
A
Annie_wang 已提交
3647
        console.info('Succeeded in closing result set');
A
Annie_wang 已提交
3648
    }).catch((err) => {
A
Annie_wang 已提交
3649
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3650 3651
    });
} catch (e) {
J
Jiefeng Li 已提交
3652
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677
}
```

### closeResultSet

closeResultSet(resultSet: KVStoreResultSet, callback: AsyncCallback&lt;void&gt;): void

Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type                             | Mandatory| Description                              |
| --------- | ------------------------------------- | ---- | ---------------------------------- |
| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes  | **KVStoreResultSet** object to close.|
| callback  | AsyncCallback&lt;void&gt;             | Yes  | Callback invoked to return the result.                        |

**Example**

```js
try {
    let resultSet = null;
    kvStore.closeResultSet(resultSet, function (err, data) {
        if (err == undefined) {
A
Annie_wang 已提交
3678
            console.info('Succeeded in closing result set');
A
Annie_wang 已提交
3679
        } else {
A
Annie_wang 已提交
3680
            console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3681 3682 3683
        }
    });
} catch (e) {
J
Jiefeng Li 已提交
3684
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713
}
```

### closeResultSet

closeResultSet(resultSet: KVStoreResultSet): Promise&lt;void&gt;

Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type                             | Mandatory| Description                              |
| --------- | ------------------------------------- | ---- | ---------------------------------- |
| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes  | **KVStoreResultSet** object to close.|

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Example**

```js
try {
    let resultSet = null;
    kvStore.closeResultSet(resultSet).then(() => {
A
Annie_wang 已提交
3714
        console.info('Succeeded in closing result set');
A
Annie_wang 已提交
3715
    }).catch((err) => {
A
Annie_wang 已提交
3716
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3717 3718
    });
} catch (e) {
J
Jiefeng Li 已提交
3719
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734
}
```

### getResultSize

getResultSize(query: Query, callback: AsyncCallback&lt;number&gt;): void

Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                   | Mandatory| Description                                       |
| -------- | --------------------------- | ---- | ------------------------------------------- |
A
Annie_wang 已提交
3735
| query    | [Query](#query)              | Yes  | **Query** object to match.                             |
A
Annie_wang 已提交
3736 3737 3738 3739 3740 3741
| callback | AsyncCallback&lt;number&gt; | Yes  | Callback invoked to return the number of results obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3742
| ID| **Error Message**                          |
A
Annie_wang 已提交
3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries, async function (err, data) {
A
Annie_wang 已提交
3764
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
3765 3766 3767 3768
        const query = new distributedKVStore.Query();
        query.prefixKey("batch_test");
        kvStore.getResultSize(query, async function (err, resultSize) {
            if (err != undefined) {
A
Annie_wang 已提交
3769
                console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3770 3771
                return;
            }
A
Annie_wang 已提交
3772
            console.info('Succeeded in getting result set size');
A
Annie_wang 已提交
3773 3774 3775
        });
    });
} catch (e) {
J
Jiefeng Li 已提交
3776
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791
}
```

### getResultSize

getResultSize(query: Query): Promise&lt;number&gt;

Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type      | Mandatory| Description          |
| ------ | -------------- | ---- | -------------- |
A
Annie_wang 已提交
3792
| query  | [Query](#query) | Yes  | **Query** object to match.|
A
Annie_wang 已提交
3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803

**Return value**

| Type                 | Description                                           |
| --------------------- | ----------------------------------------------- |
| Promise&lt;number&gt; | Promise used to return the number of results obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3804
| ID| **Error Message**                          |
A
Annie_wang 已提交
3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
3826
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
3827
    }).catch((err) => {
A
Annie_wang 已提交
3828
        console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3829 3830 3831 3832
    });
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    kvStore.getResultSize(query).then((resultSize) => {
A
Annie_wang 已提交
3833
        console.info('Succeeded in getting result set size');
A
Annie_wang 已提交
3834
    }).catch((err) => {
A
Annie_wang 已提交
3835
        console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3836 3837
    });
} catch (e) {
J
Jiefeng Li 已提交
3838
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860
}
```

### backup

backup(file:string, callback: AsyncCallback&lt;void&gt;):void

Backs up a distributed KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                 | Mandatory| Description                                                        |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| file     | string                    | Yes  | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).|
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3861
| ID| **Error Message**                          |
A
Annie_wang 已提交
3862 3863 3864 3865 3866 3867 3868 3869 3870 3871
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
let file = "BK001";
try {
    kvStore.backup(file, (err, data) => {
        if (err) {
A
Annie_wang 已提交
3872
            console.error(`Failed to backup.code is ${err.code},message is ${err.message} `);
A
Annie_wang 已提交
3873
        } else {
A
Annie_wang 已提交
3874
            console.info(`Succeeded in backupping data.data=${data}`);
A
Annie_wang 已提交
3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905
        }
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### backup

backup(file:string): Promise&lt;void&gt;

Backs up an RDB store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                                                        |
| ------ | -------- | ---- | ------------------------------------------------------------ |
| file   | string   | Yes  | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).|

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3906
| ID| **Error Message**                          |
A
Annie_wang 已提交
3907 3908 3909 3910 3911 3912 3913 3914 3915
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
let file = "BK001";
try {
    kvStore.backup(file).then((data) => {
A
Annie_wang 已提交
3916
        console.info(`Succeeded in backupping data.data=${data}`);
A
Annie_wang 已提交
3917
    }).catch((err) => {
A
Annie_wang 已提交
3918
        console.error(`Failed to backup.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### restore

restore(file:string, callback: AsyncCallback&lt;void&gt;):void

Restores a distributed KV store from a database file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                 | Mandatory| Description                                                        |
| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| file     | string                    | Yes  | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).|
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3944
| ID| **Error Message**                          |
A
Annie_wang 已提交
3945 3946 3947 3948 3949 3950 3951 3952 3953 3954
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
let file = "BK001";
try {
    kvStore.restore(file, (err, data) => {
        if (err) {
A
Annie_wang 已提交
3955
            console.error(`Failed to restore.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
3956
        } else {
A
Annie_wang 已提交
3957
            console.info(`Succeeded in restoring data.data=${data}`);
A
Annie_wang 已提交
3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988
        }
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### restore

restore(file:string): Promise&lt;void&gt;

Restores a distributed KV store from a database file. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type| Mandatory| Description                                                        |
| ------ | -------- | ---- | ------------------------------------------------------------ |
| file   | string   | Yes  | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).|

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
3989
| ID| **Error Message**                          |
A
Annie_wang 已提交
3990 3991 3992 3993 3994 3995 3996 3997 3998
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
let file = "BK001";
try {
    kvStore.restore(file).then((data) => {
A
Annie_wang 已提交
3999
        console.info(`Succeeded in restoring data.data=${data}`);
A
Annie_wang 已提交
4000
    }).catch((err) => {
A
Annie_wang 已提交
4001
        console.error(`Failed to restore.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### deleteBackup

deleteBackup(files:Array&lt;string&gt;, callback: AsyncCallback&lt;Array&lt;[string, number]&gt;&gt;):void

Deletes a backup file. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                                          | Mandatory| Description                                                        |
| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ |
| files    | Array&lt;string&gt;                                | Yes  | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).|
| callback | AsyncCallback&lt;Array&lt;[string, number]&gt;&gt; | Yes  | Callback invoked to return the name of the backup file deleted and the operation result.                |

**Example**

```js
let files = ["BK001", "BK002"];
try {
    kvStore.deleteBackup(files, (err, data) => {
        if (err) {
A
Annie_wang 已提交
4030
            console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4031
        } else {
A
Annie_wang 已提交
4032
            console.info(`Succeed in deleting Backup.data=${data}`);
A
Annie_wang 已提交
4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065
        }
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
}
```

### deleteBackup

deleteBackup(files:Array&lt;string&gt;): Promise&lt;Array&lt;[string, number]&gt;&gt;

Deletes a backup file. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type           | Mandatory| Description                                                        |
| ------ | ------------------- | ---- | ------------------------------------------------------------ |
| files  | Array&lt;string&gt; | Yes  | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).|

**Return value**

| Type                                        | Description                                           |
| -------------------------------------------- | ----------------------------------------------- |
| Promise&lt;Array&lt;[string, number]&gt;&gt; | Promise used to return the name of the backup file deleted and the operation result.|

**Example**

```js
let files = ["BK001", "BK002"];
try {
    kvStore.deleteBackup(files).then((data) => {
A
Annie_wang 已提交
4066
        console.info(`Succeed in deleting Backup.data=${data}`);
A
Annie_wang 已提交
4067
    }).catch((err) => {
A
Annie_wang 已提交
4068
        console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4069 4070
    })
} catch (e) {
A
Annie_wang 已提交
4071
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092
}
```

### startTransaction

startTransaction(callback: AsyncCallback&lt;void&gt;): void

Starts the transaction in this single KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                 | Mandatory| Description      |
| -------- | ------------------------- | ---- | ---------- |
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4093 4094 4095 4096 4097 4098 4099 4100 4101
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123

**Example**

```js
function putBatchString(len, prefix) {
    let entries = [];
    for (var i = 0; i < len; i++) {
        var entry = {
            key: prefix + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    return entries;
}

try {
    var count = 0;
    kvStore.on('dataChange', 0, function (data) {
A
Annie_wang 已提交
4124
        console.info(`startTransaction 0 ${data}`);
A
Annie_wang 已提交
4125 4126 4127 4128
        count++;
    });
    kvStore.startTransaction(async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
4129
            console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4130 4131
            return;
        }
A
Annie_wang 已提交
4132
        console.info('Succeeded in starting Transaction');
A
Annie_wang 已提交
4133
        let entries = putBatchString(10, 'batch_test_string_key');
A
Annie_wang 已提交
4134
        console.info(`entries: ${entries}`);
A
Annie_wang 已提交
4135 4136
        kvStore.putBatch(entries, async function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
4137
                console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4138 4139
                return;
            }
A
Annie_wang 已提交
4140
            console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
4141 4142 4143
        });
    });
} catch (e) {
A
Annie_wang 已提交
4144
    console.error(`Failed to start Transaction.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165
}
```

### startTransaction

startTransaction(): Promise&lt;void&gt;

Starts the transaction in this single KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4166 4167 4168 4169 4170 4171 4172 4173 4174
| ID| **Error Message**                            |
| ------------ | ---------------------------------------- |
| 15100005     | Database or result set already closed.   |

For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).

| ID| **Error Message**                                |
| ------------ | -------------------------------------------- |
| 14800047     | The WAL file size exceeds the default limit. |
A
Annie_wang 已提交
4175 4176 4177 4178 4179 4180 4181

**Example**

```js
try {
    var count = 0;
    kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
A
Annie_wang 已提交
4182
        console.info(`startTransaction 0 ${data}`);
A
Annie_wang 已提交
4183 4184 4185
        count++;
    });
    kvStore.startTransaction().then(async (err) => {
A
Annie_wang 已提交
4186
        console.info('Succeeded in starting Transaction');
A
Annie_wang 已提交
4187
    }).catch((err) => {
A
Annie_wang 已提交
4188
        console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4189 4190
    });
} catch (e) {
A
Annie_wang 已提交
4191
    console.error(`Failed to start Transaction.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212
}
```

### commit

commit(callback: AsyncCallback&lt;void&gt;): void

Commits the transaction in this single KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                 | Mandatory| Description      |
| -------- | ------------------------- | ---- | ---------- |
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4213
| ID| **Error Message**                          |
A
Annie_wang 已提交
4214 4215 4216 4217 4218 4219 4220 4221 4222
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    kvStore.commit(function (err, data) {
        if (err == undefined) {
A
Annie_wang 已提交
4223
            console.info('Succeeded in committing');
A
Annie_wang 已提交
4224
        } else {
A
Annie_wang 已提交
4225
            console.error(`Failed to commit.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4226 4227 4228
        }
    });
} catch (e) {
J
Jiefeng Li 已提交
4229
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250
}
```

### commit

commit(): Promise&lt;void&gt;

Commits the transaction in this single KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4251
| ID| **Error Message**                          |
A
Annie_wang 已提交
4252 4253 4254 4255 4256 4257 4258 4259
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    kvStore.commit().then(async (err) => {
A
Annie_wang 已提交
4260
        console.info('Succeeded in committing');
A
Annie_wang 已提交
4261
    }).catch((err) => {
A
Annie_wang 已提交
4262
        console.error(`Failed to commit.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4263 4264
    });
} catch (e) {
J
Jiefeng Li 已提交
4265
    console.error(`An unexpected error occurred.ode is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286
}
```

### rollback

rollback(callback: AsyncCallback&lt;void&gt;): void

Rolls back the transaction in this single KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                 | Mandatory| Description      |
| -------- | ------------------------- | ---- | ---------- |
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4287
| ID| **Error Message**                          |
A
Annie_wang 已提交
4288 4289 4290 4291 4292 4293 4294 4295 4296
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    kvStore.rollback(function (err,data) {
        if (err == undefined) {
A
Annie_wang 已提交
4297
            console.info('Succeeded in rolling back');
A
Annie_wang 已提交
4298
        } else {
A
Annie_wang 已提交
4299
            console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4300 4301 4302
        }
    });
}catch(e) {
J
Jiefeng Li 已提交
4303
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324
}
```

### rollback

rollback(): Promise&lt;void&gt;

Rolls back the transaction in this single KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4325
| ID| **Error Message**                          |
A
Annie_wang 已提交
4326 4327 4328 4329 4330 4331 4332 4333
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    kvStore.rollback().then(async (err) => {
A
Annie_wang 已提交
4334
        console.info('Succeeded in rolling back');
A
Annie_wang 已提交
4335
    }).catch((err) => {
A
Annie_wang 已提交
4336
        console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4337 4338
    });
} catch (e) {
J
Jiefeng Li 已提交
4339
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363
}
```

### enableSync

enableSync(enabled: boolean, callback: AsyncCallback&lt;void&gt;): void

Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                 | Mandatory| Description                                                     |
| -------- | ------------------------- | ---- | --------------------------------------------------------- |
| enabled  | boolean                   | Yes  | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.|
| callback | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.                                               |

**Example**

```js
try {
    kvStore.enableSync(true, function (err, data) {
        if (err == undefined) {
A
Annie_wang 已提交
4364
            console.info('Succeeded in enabling sync');
A
Annie_wang 已提交
4365
        } else {
A
Annie_wang 已提交
4366
            console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4367 4368 4369
        }
    });
} catch (e) {
J
Jiefeng Li 已提交
4370
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398
}
```

### enableSync

enableSync(enabled: boolean): Promise&lt;void&gt;

Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name | Type| Mandatory| Description                                                     |
| ------- | -------- | ---- | --------------------------------------------------------- |
| enabled | boolean  | Yes  | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.|

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Example**

```js
try {
    kvStore.enableSync(true).then((err) => {
A
Annie_wang 已提交
4399
        console.info('Succeeded in enabling sync');
A
Annie_wang 已提交
4400
    }).catch((err) => {
A
Annie_wang 已提交
4401
        console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4402 4403
    });
} catch (e) {
J
Jiefeng Li 已提交
4404
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431
}
```

### setSyncRange

setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback&lt;void&gt;): void

Sets the data synchronization range. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name             | Type                 | Mandatory| Description                            |
| ------------------- | ------------------------- | ---- | -------------------------------- |
| localLabels         | string[]                  | Yes  | Synchronization labels set for the local device.        |
| remoteSupportLabels | string[]                  | Yes  | Synchronization labels set for remote devices.|
| callback            | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.                      |

**Example**

```js
try {
    const localLabels = ['A', 'B'];
    const remoteSupportLabels = ['C', 'D'];
    kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
4432
            console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4433 4434
            return;
        }
A
Annie_wang 已提交
4435
        console.info('Succeeded in setting syncRange');
A
Annie_wang 已提交
4436 4437
    });
} catch (e) {
J
Jiefeng Li 已提交
4438
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469
}
```

### setSyncRange

setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise&lt;void&gt;

Sets the data synchronization range. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name             | Type| Mandatory| Description                            |
| ------------------- | -------- | ---- | -------------------------------- |
| localLabels         | string[] | Yes  | Synchronization labels set for the local device.        |
| remoteSupportLabels | string[] | Yes  | Synchronization labels set for remote devices.|

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Example**

```js
try {
    const localLabels = ['A', 'B'];
    const remoteSupportLabels = ['C', 'D'];
    kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => {
A
Annie_wang 已提交
4470
        console.info('Succeeded in setting syncRange');
A
Annie_wang 已提交
4471
    }).catch((err) => {
A
Annie_wang 已提交
4472
        console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4473 4474
    });
} catch (e) {
J
Jiefeng Li 已提交
4475
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500
}
```

### setSyncParam

setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback&lt;void&gt;): void

Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name               | Type                 | Mandatory| Description                                        |
| --------------------- | ------------------------- | ---- | -------------------------------------------- |
| defaultAllowedDelayMs | number                    | Yes  | Default delay allowed for database synchronization, in ms.|
| callback              | AsyncCallback&lt;void&gt; | Yes  | Callback invoked to return the result.                                  |

**Example**

```js
try {
    const defaultAllowedDelayMs = 500;
    kvStore.setSyncParam(defaultAllowedDelayMs, function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
4501
            console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4502 4503
            return;
        }
A
Annie_wang 已提交
4504
        console.info('Succeeded in setting syncParam');
A
Annie_wang 已提交
4505 4506
    });
} catch (e) {
J
Jiefeng Li 已提交
4507
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536
}
```

### setSyncParam

setSyncParam(defaultAllowedDelayMs: number): Promise&lt;void&gt;

Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name               | Type| Mandatory| Description                                        |
| --------------------- | -------- | ---- | -------------------------------------------- |
| defaultAllowedDelayMs | number   | Yes  | Default delay allowed for database synchronization, in ms.|

**Return value**

| Type               | Description                     |
| ------------------- | ------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|

**Example**

```js
try {
    const defaultAllowedDelayMs = 500;
    kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => {
A
Annie_wang 已提交
4537
        console.info('Succeeded in setting syncParam');
A
Annie_wang 已提交
4538
    }).catch((err) => {
A
Annie_wang 已提交
4539
        console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4540 4541
    });
} catch (e) {
J
Jiefeng Li 已提交
4542
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4543 4544 4545 4546 4547 4548 4549
}
```

### sync

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

A
Annie_wang 已提交
4550
Synchronizes the KV store manually. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md).
A
Annie_wang 已提交
4551
> **NOTE**
A
Annie_wang 已提交
4552 4553
>
> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
A
Annie_wang 已提交
4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570

**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type             | Mandatory| Description                                          |
| --------- | --------------------- | ---- | ---------------------------------------------- |
| deviceIds | string[]              | Yes  | List of IDs of the devices in the same networking environment to be synchronized.|
| mode      | [SyncMode](#syncmode) | Yes  | Synchronization mode.                                    |
| delayMs   | number                | No  | Allowed synchronization delay time, in ms.    |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4571
| ID| **Error Message**       |
A
Annie_wang 已提交
4572 4573 4574 4575 4576 4577 4578
| ------------ | ------------------- |
| 15100003     | Database corrupted. |
| 15100004     | Not found.          |

**Example**

```js
A
Annie_wang 已提交
4579 4580 4581
import deviceManager from '@ohos.distributedHardware.deviceManager';

let devManager;
A
Annie_wang 已提交
4582 4583
const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
A
Annie_wang 已提交
4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596
// create deviceManager
deviceManager.createDeviceManager('bundleName', (err, value) => {
  if (!err) {
    devManager = value;
    let deviceIds = [];
    if (devManager != null) {
      var devices = devManager.getTrustedDeviceListSync();
      for (var i = 0; i < devices.length; i++) {
        deviceIds[i] = devices[i].deviceId;
      }
    }
    try {
      kvStore.on('syncComplete', function (data) {
A
Annie_wang 已提交
4597
        console.info('Sync dataChange');
A
Annie_wang 已提交
4598 4599
      });
      kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) {
A
Annie_wang 已提交
4600
        if (err != undefined) {
A
Annie_wang 已提交
4601
          console.error(`Failed to sync.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4602
          return;
A
Annie_wang 已提交
4603
        }
A
Annie_wang 已提交
4604
        console.info('Succeeded in putting data');
A
Annie_wang 已提交
4605
        const mode = distributedKVStore.SyncMode.PULL_ONLY;
A
Annie_wang 已提交
4606 4607 4608
        kvStore.sync(deviceIds, mode, 1000);
      });
    } catch (e) {
A
Annie_wang 已提交
4609
      console.error(`Failed to sync.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4610 4611 4612
    }
  }
});
A
Annie_wang 已提交
4613 4614 4615 4616 4617 4618
```

### sync

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

A
Annie_wang 已提交
4619
Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md).
A
Annie_wang 已提交
4620
> **NOTE**
A
Annie_wang 已提交
4621 4622
>
> The value of **deviceIds** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
A
Annie_wang 已提交
4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633

**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type             | Mandatory| Description                                          |
| --------- | --------------------- | ---- | ---------------------------------------------- |
| deviceIds | string[]              | Yes  | List of IDs of the devices in the same networking environment to be synchronized.|
| mode      | [SyncMode](#syncmode) | Yes  | Synchronization mode.                                    |
A
Annie_wang 已提交
4634
| query     | [Query](#query)        | Yes  | **Query** object to match.                      |
A
Annie_wang 已提交
4635 4636 4637 4638 4639 4640
| delayMs   | number                | No  | Allowed synchronization delay time, in ms.    |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4641
| ID| **Error Message**       |
A
Annie_wang 已提交
4642 4643 4644 4645 4646 4647 4648
| ------------ | ------------------- |
| 15100003     | Database corrupted. |
| 15100004     | Not found.          |

**Example**

```js
A
Annie_wang 已提交
4649 4650 4651
import deviceManager from '@ohos.distributedHardware.deviceManager';

let devManager;
A
Annie_wang 已提交
4652 4653
const KEY_TEST_SYNC_ELEMENT = 'key_test_sync';
const VALUE_TEST_SYNC_ELEMENT = 'value-string-001';
A
Annie_wang 已提交
4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666
// create deviceManager
deviceManager.createDeviceManager('bundleName', (err, value) => {
  if (!err) {
    devManager = value;
    let deviceIds = [];
    if (devManager != null) {
      var devices = devManager.getTrustedDeviceListSync();
      for (var i = 0; i < devices.length; i++) {
        deviceIds[i] = devices[i].deviceId;
      }
    }
    try {
      kvStore.on('syncComplete', function (data) {
A
Annie_wang 已提交
4667
        console.info('Sync dataChange');
A
Annie_wang 已提交
4668 4669
      });
      kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) {
A
Annie_wang 已提交
4670
        if (err != undefined) {
A
Annie_wang 已提交
4671
          console.error(`Failed to sync.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4672
          return;
A
Annie_wang 已提交
4673
        }
A
Annie_wang 已提交
4674
        console.info('Succeeded in putting data');
A
Annie_wang 已提交
4675 4676 4677 4678
        const mode = distributedKVStore.SyncMode.PULL_ONLY;
        const query = new distributedKVStore.Query();
        query.prefixKey("batch_test");
        query.deviceId('localDeviceId');
A
Annie_wang 已提交
4679 4680 4681
        kvStore.sync(deviceIds, query, mode, 1000);
      });
    } catch (e) {
A
Annie_wang 已提交
4682
      console.error(`Failed to sync.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4683 4684 4685
    }
  }
});
A
Annie_wang 已提交
4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701
```

### on('dataChange')

on(event: 'dataChange', type: SubscribeType, listener: Callback&lt;ChangeNotification&gt;): void

Subscribes to data changes of the specified type.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                                                 | Mandatory| Description                                                |
| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- |
| event    | string                                                    | Yes  | Event to subscribe to. The value is **dataChange**, which indicates a data change event.|
| type     | [SubscribeType](#subscribetype)                           | Yes  | Type of data change.                                    |
A
Annie_wang 已提交
4702
| listener | Callback&lt;[ChangeNotification](#changenotification)&gt; | Yes  | Callback invoked to return the data change.                         |
A
Annie_wang 已提交
4703 4704 4705 4706 4707

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4708
| ID| **Error Message**                          |
A
Annie_wang 已提交
4709
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
4710
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
4711 4712 4713 4714 4715 4716 4717
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) {
A
Annie_wang 已提交
4718
        console.info(`dataChange callback call data: ${data}`);
A
Annie_wang 已提交
4719 4720
    });
} catch (e) {
J
Jiefeng Li 已提交
4721
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737
}
```

### on('syncComplete')

on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void

Subscribes to synchronization complete events.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name      | Type                                     | Mandatory| Description                                                  |
| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ |
| event        | string                                        | Yes  | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.|
A
Annie_wang 已提交
4738
| syncCallback | Callback&lt;Array&lt;[string, number]&gt;&gt; | Yes  | Callback invoked to return the synchronization complete event.|
A
Annie_wang 已提交
4739 4740 4741 4742 4743 4744 4745 4746

**Example**

```js
const KEY_TEST_FLOAT_ELEMENT = 'key_test_float';
const VALUE_TEST_FLOAT_ELEMENT = 321.12;
try {
    kvStore.on('syncComplete', function (data) {
A
Annie_wang 已提交
4747
        console.info(`syncComplete ${data}`);
A
Annie_wang 已提交
4748 4749
    });
    kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => {
A
Annie_wang 已提交
4750
        console.info('succeeded in putting');
A
Annie_wang 已提交
4751
    }).catch((err) => {
A
Annie_wang 已提交
4752
        console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4753 4754
    });
} catch (e) {
A
Annie_wang 已提交
4755
    console.error(`Failed to subscribe syncComplete.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771
}
```

### off('dataChange')

off(event:'dataChange', listener?: Callback&lt;ChangeNotification&gt;): void

Unsubscribes from data changes.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                                                 | Mandatory| Description                                                    |
| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- |
| event    | string                                                    | Yes  | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.|
A
Annie_wang 已提交
4772
| listener | Callback&lt;[ChangeNotification](#changenotification)&gt; | No  | Callback for the data change event.                                              |
A
Annie_wang 已提交
4773 4774 4775 4776 4777

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4778
| ID| **Error Message**                          |
A
Annie_wang 已提交
4779 4780 4781 4782 4783 4784 4785 4786
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
class KvstoreModel {
    call(data) {
A
Annie_wang 已提交
4787
        console.info(`dataChange : ${data}`);
A
Annie_wang 已提交
4788 4789 4790 4791 4792 4793 4794 4795
    }

    subscribeDataChange() {
        try {
            if (kvStore != null) {
                kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call);
            }
        } catch (err) {
A
Annie_wang 已提交
4796
            console.error(`Failed to subscribeDataChange.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4797 4798 4799 4800 4801 4802 4803 4804 4805
        }
    }

    unsubscribeDataChange() {
        try {
            if (kvStore != null) {
                kvStore.off('dataChange', this.call);
            }
        } catch (err) {
A
Annie_wang 已提交
4806
            console.error(`Failed to unsubscribeDataChange.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824
        }
    }
}
```

### off('syncComplete')

off(event: 'syncComplete', syncCallback?: Callback&lt;Array&lt;[string, number]&gt;&gt;): void

Unsubscribes from synchronization complete events.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name      | Type                                     | Mandatory| Description                                                      |
| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- |
| event        | string                                        | Yes  | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.|
A
Annie_wang 已提交
4825
| syncCallback | Callback&lt;Array&lt;[string, number]&gt;&gt; | No  | Callback for the synchronization complete event.                |
A
Annie_wang 已提交
4826 4827 4828 4829 4830 4831

**Example**

```js
class KvstoreModel {
    call(data) {
A
Annie_wang 已提交
4832
        console.info(`syncComplete : ${data}`);
A
Annie_wang 已提交
4833 4834 4835 4836 4837 4838 4839 4840
    }

    subscribeDataChange() {
        try {
            if (kvStore != null) {
                kvStore.on('syncComplete', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call);
            }
        } catch (err) {
A
Annie_wang 已提交
4841
            console.error(`Failed to subscribeDataChange.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4842 4843 4844 4845 4846 4847 4848 4849 4850
        }
    }

    unsubscribeDataChange() {
        try {
            if (kvStore != null) {
                kvStore.off('dsyncComplete', this.call);
            }
        } catch (err) {
A
Annie_wang 已提交
4851
            console.error(`Failed to unsubscribeDataChange.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874
        }
    }
}
```

### getSecurityLevel

getSecurityLevel(callback: AsyncCallback&lt;SecurityLevel&gt;): void

Obtains the security level of this KV store. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                                            | Mandatory| Description                            |
| -------- | ---------------------------------------------------- | ---- | -------------------------------- |
| callback | AsyncCallback&lt;[SecurityLevel](#securitylevel)&gt; | Yes  | Callback invoked to return the security level obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4875
| ID| **Error Message**                          |
A
Annie_wang 已提交
4876 4877 4878 4879 4880 4881 4882 4883 4884
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    kvStore.getSecurityLevel(function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
4885
            console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4886 4887
            return;
        }
A
Annie_wang 已提交
4888
        console.info('Succeeded in getting securityLevel');
A
Annie_wang 已提交
4889 4890
    });
} catch (e) {
J
Jiefeng Li 已提交
4891
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912
}
```

### getSecurityLevel

getSecurityLevel(): Promise&lt;SecurityLevel&gt;

Obtains the security level of this KV store. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Return value**

| Type                                          | Description                               |
| ---------------------------------------------- | ----------------------------------- |
| Promise&lt;[SecurityLevel](#securitylevel)&gt; | Promise used to return the security level obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4913
| ID| **Error Message**                          |
A
Annie_wang 已提交
4914 4915 4916 4917 4918 4919 4920 4921
| ------------ | -------------------------------------- |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    kvStore.getSecurityLevel().then((data) => {
A
Annie_wang 已提交
4922
        console.info('Succeeded in getting securityLevel');
A
Annie_wang 已提交
4923
    }).catch((err) => {
A
Annie_wang 已提交
4924
        console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4925 4926
    });
} catch (e) {
J
Jiefeng Li 已提交
4927
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942
}
```

## DeviceKVStore

Provides APIs for querying and synchronizing data in a device KV store. This class inherits from **SingleKVStore**.

Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified.

For example, a device KV store can be used to implement image sharing between devices. The images of other devices can be viewed, but not be modified or deleted.

Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object.

### get

A
Annie_wang 已提交
4943
get(key: string, callback: AsyncCallback&lt;boolean | string | number | Uint8Array&gt;): void
A
Annie_wang 已提交
4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959

Obtains the value of the specified key for this device. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                                                        | Mandatory| Description                                                        |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| key      | string                                                       | Yes  | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).|
| callback | AsyncCallback&lt;boolean \| string \| number \| Uint8Array&gt; | Yes  | Callback invoked to return the value obtained.                                |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
4960
| ID| **Error Message**                          |
A
Annie_wang 已提交
4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100004     | Not found.                             |
| 15100005     | Database or result set already closed. |

**Example**

```js
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, function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
4974
            console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4975 4976
            return;
        }
A
Annie_wang 已提交
4977
        console.info("Succeeded in putting");
A
Annie_wang 已提交
4978 4979
        kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
4980
                console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
4981 4982
                return;
            }
A
Annie_wang 已提交
4983
            console.info(`Succeeded in getting data.data=${data}`);
A
Annie_wang 已提交
4984 4985 4986
        });
    });
} catch (e) {
A
Annie_wang 已提交
4987
    console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
4988 4989 4990 4991 4992
}
```

### get

A
Annie_wang 已提交
4993
get(key: string): Promise&lt;boolean | string | number | Uint8Array&gt;
A
Annie_wang 已提交
4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014

Obtains the value of the specified key for this device. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type  | Mandatory| Description                                                        |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| key    | string | Yes  | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).|

**Return value**

| Type                                                    | Description                           |
| -------------------------------------------------------- | ------------------------------- |
| Promise&lt;Uint8Array \| string \| boolean \| number&gt; | Promise used to return the value obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5015
| ID| **Error Message**                          |
A
Annie_wang 已提交
5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100004     | Not found.                             |
| 15100005     | Database or result set already closed. |

**Example**

```js
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((data) => {
A
Annie_wang 已提交
5028
        console.info(`Succeeded in putting data.data=${data}`);
A
Annie_wang 已提交
5029
        kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => {
A
Annie_wang 已提交
5030
            console.info(`Succeeded in getting data.data=${data}`);
A
Annie_wang 已提交
5031
        }).catch((err) => {
A
Annie_wang 已提交
5032
            console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5033 5034
        });
    }).catch((err) => {
A
Annie_wang 已提交
5035
        console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5036 5037
    });
} catch (e) {
A
Annie_wang 已提交
5038
    console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5039 5040 5041 5042 5043
}
```

### get

A
Annie_wang 已提交
5044
get(deviceId: string, key: string, callback: AsyncCallback&lt;boolean | string | number | Uint8Array&gt;): void
A
Annie_wang 已提交
5045 5046

Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
5047
> **NOTE**
A
Annie_wang 已提交
5048 5049 5050
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name | Type| Mandatory | Description                   |
| -----  | ------   | ----  | ----------------------- |
| deviceId  |string  | Yes   |ID of the target device.   |
| key       |string  | Yes   |Key to match.   |
| callback  |AsyncCallback&lt;boolean\|string\|number\|Uint8Array&gt;  | Yes   |Callback invoked to return the value obtained.   |

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5066
| ID| **Error Message**                          |
A
Annie_wang 已提交
5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100004     | Not found.                             |
| 15100005     | Database or result set already closed. |

**Example**

```js
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 function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
5080
            console.error(`Failed to put.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5081 5082
            return;
        }
A
Annie_wang 已提交
5083
        console.info('Succeeded in putting');
A
Annie_wang 已提交
5084 5085
        kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
5086
                console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5087 5088
                return;
            }
A
Annie_wang 已提交
5089
            console.info('Succeeded in getting');
A
Annie_wang 已提交
5090 5091 5092
        });
    })
} catch (e) {
A
Annie_wang 已提交
5093
    console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5094 5095 5096 5097 5098
}
```

### get

A
Annie_wang 已提交
5099
get(deviceId: string, key: string): Promise&lt;boolean | string | number | Uint8Array&gt;
A
Annie_wang 已提交
5100 5101

Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result.
A
Annie_wang 已提交
5102
> **NOTE**
A
Annie_wang 已提交
5103 5104 5105
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name  | Type| Mandatory| Description                    |
| -------- | -------- | ---- | ------------------------ |
| deviceId | string   | Yes  | ID of the target device.|
| key      | string   | Yes  | Key to match.   |

**Return value**

| Type   | Description      |
| ------  | -------   |
A
Annie_wang 已提交
5120
|Promise&lt;boolean\|string\|number\|Uint8Array&gt; |Promise used to return the string value that matches the given condition.|
A
Annie_wang 已提交
5121 5122 5123 5124 5125

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5126
| ID| **Error Message**                          |
A
Annie_wang 已提交
5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100004     | Not found.                             |
| 15100005     | Database or result set already closed. |

**Example**

```js
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 (data) => {
A
Annie_wang 已提交
5139
        console.info('Succeeded in putting');
A
Annie_wang 已提交
5140
        kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => {
A
Annie_wang 已提交
5141
            console.info('Succeeded in getting');
A
Annie_wang 已提交
5142
        }).catch((err) => {
A
Annie_wang 已提交
5143
            console.error(`Failed to get.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5144 5145
        });
    }).catch((error) => {
A
Annie_wang 已提交
5146
        console.error(`Failed to put.code is ${error.code},message is ${error.message}`);
A
Annie_wang 已提交
5147 5148
    });
} catch (e) {
A
Annie_wang 已提交
5149
    console.error(`Failed to get.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165
}
```

### getEntries

getEntries(keyPrefix: string, callback: AsyncCallback&lt;Entry[]&gt;): void

Obtains all KV pairs that match the specified key prefix for this device. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type                                  | Mandatory| Description                                    |
| --------- | -------------------------------------- | ---- | ---------------------------------------- |
| keyPrefix | string                                 | Yes  | Key prefix to match.                    |
A
Annie_wang 已提交
5166
| callback  | AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes  | Callback invoked to return the KV pairs that match the specified prefix.|
A
Annie_wang 已提交
5167 5168 5169 5170 5171

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5172
| ID| **Error Message**                          |
A
Annie_wang 已提交
5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
5193
    console.info(`entries: ${entries}`);
A
Annie_wang 已提交
5194 5195
    kvStore.putBatch(entries, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
5196
            console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5197 5198
            return;
        }
A
Annie_wang 已提交
5199
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
5200 5201
        kvStore.getEntries('batch_test_string_key', function (err, entries) {
            if (err != undefined) {
A
Annie_wang 已提交
5202
                console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5203 5204
                return;
            }
A
Annie_wang 已提交
5205 5206 5207
            console.info('Succeeded in getting Entries');
            console.info(`entries.length: ${entries.length}`);
            console.info(`entries[0]: ${entries[0]}`);
A
Annie_wang 已提交
5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232
        });
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `);
}
```

### getEntries

getEntries(keyPrefix: string): Promise&lt;Entry[]&gt;

Obtains all KV pairs that match the specified key prefix for this device. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type  | Mandatory| Description                |
| --------- | ------ | ---- | -------------------- |
| keyPrefix | string | Yes  | Key prefix to match.|

**Return value**

| Type                            | Description                                       |
| -------------------------------- | ------------------------------------------- |
A
Annie_wang 已提交
5233
| Promise&lt;[Entry](#entry)[]&gt; | Promise used to return the KV pairs that match the specified prefix.|
A
Annie_wang 已提交
5234 5235 5236 5237 5238

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5239
| ID| **Error Message**                          |
A
Annie_wang 已提交
5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
5260
    console.info(`entries: ${entries}`);
A
Annie_wang 已提交
5261
    kvStore.putBatch(entries).then(async (entries) => {
A
Annie_wang 已提交
5262
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
5263
        kvStore.getEntries('batch_test_string_key').then((entries) => {
A
Annie_wang 已提交
5264 5265
            console.info('Succeeded in getting Entries');
            console.info(`PutBatch ${entries}`);
A
Annie_wang 已提交
5266
        }).catch((err) => {
A
Annie_wang 已提交
5267
            console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5268 5269
        });
    }).catch((err) => {
A
Annie_wang 已提交
5270
        console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281
    });
} catch (e) {
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `);
}
```

### getEntries

getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;Entry[]&gt;): void

Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
5282
> **NOTE**
A
Annie_wang 已提交
5283 5284 5285
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name   | Type                              | Mandatory| Description                                          |
| --------- | -------------------------------------- | ---- | ---------------------------------------------- |
| deviceId  | string                                 | Yes  | ID of the target device.                      |
| keyPrefix | string                                 | Yes  | Key prefix to match.                          |
| callback  | AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes  | Callback invoked to return the KV pairs obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5301
| ID| **Error Message**                          |
A
Annie_wang 已提交
5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
5322
    console.info(`entries : ${entries}`);
A
Annie_wang 已提交
5323 5324
    kvStore.putBatch(entries, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
5325
            console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5326 5327
            return;
        }
A
Annie_wang 已提交
5328
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
5329 5330
        kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err, entries) {
            if (err != undefined) {
A
Annie_wang 已提交
5331
                console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5332 5333
                return;
            }
A
Annie_wang 已提交
5334 5335 5336
            console.info('Succeeded in getting entries');
            console.info(`entries.length: ${entries.length}`);
            console.info(`entries[0]: ${entries[0]}`);
A
Annie_wang 已提交
5337 5338 5339
        });
    });
} catch (e) {
A
Annie_wang 已提交
5340
    console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5341 5342 5343 5344 5345 5346 5347 5348
}
```

### getEntries

getEntries(deviceId: string, keyPrefix: string): Promise&lt;Entry[]&gt;

Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result.
A
Annie_wang 已提交
5349
> **NOTE**
A
Annie_wang 已提交
5350 5351 5352
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name   | Type| Mandatory| Description                    |
| --------- | -------- | ---- | ------------------------ |
| deviceId  | string   | Yes  | ID of the target device.|
| keyPrefix | string   | Yes  | Key prefix to match.    |

**Return value**

| Type                            | Description                                             |
| -------------------------------- | ------------------------------------------------- |
A
Annie_wang 已提交
5367
| Promise&lt;[Entry](#entry)[]&gt; | Promise used to return all the KV pairs that match the given condition.|
A
Annie_wang 已提交
5368 5369 5370 5371 5372

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5373
| ID| **Error Message**                          |
A
Annie_wang 已提交
5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
5394
    console.info(`entries: ${entries}`);
A
Annie_wang 已提交
5395
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
5396
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
5397
        kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => {
A
Annie_wang 已提交
5398 5399 5400 5401 5402
            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}`);
A
Annie_wang 已提交
5403
        }).catch((err) => {
A
Annie_wang 已提交
5404
            console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5405 5406
        });
    }).catch((err) => {
A
Annie_wang 已提交
5407
        console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5408 5409
    });
} catch (e) {
A
Annie_wang 已提交
5410
    console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425
}    
```

### getEntries

getEntries(query: Query, callback: AsyncCallback&lt;Entry[]&gt;): void

Obtains all KV pairs that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                                  | Mandatory| Description                                                 |
| -------- | -------------------------------------- | ---- | ----------------------------------------------------- |
A
Annie_wang 已提交
5426
| query    | [Query](#query)                         | Yes  | Key prefix to match.                                 |
A
Annie_wang 已提交
5427
| callback | AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes  | Callback invoked to return the KV pairs that match the specified **Query** object on the local device.|
A
Annie_wang 已提交
5428 5429 5430 5431 5432

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5433
| ID| **Error Message**                          |
A
Annie_wang 已提交
5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    var arr = new Uint8Array([21, 31]);
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_bool_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.BYTE_ARRAY,
                value: arr
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
5455
    console.info(`entries: {entries}`);
A
Annie_wang 已提交
5456
    kvStore.putBatch(entries, async function (err, data) {
A
Annie_wang 已提交
5457
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
5458 5459 5460 5461
        const query = new distributedKVStore.Query();
        query.prefixKey("batch_test");
        kvStore.getEntries(query, function (err, entries) {
            if (err != undefined) {
A
Annie_wang 已提交
5462
                console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5463 5464
                return;
            }
A
Annie_wang 已提交
5465 5466 5467
            console.info('Succeeded in getting Entries');
            console.info(`entries.length: ${entries.length}`);
            console.info(`entries[0]: ${entries[0]}`);
A
Annie_wang 已提交
5468 5469 5470
        });
    });
} catch (e) {
A
Annie_wang 已提交
5471
    console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486
}
```

### getEntries

getEntries(query: Query): Promise&lt;Entry[]&gt;

Obtains all KV pairs that match the specified **Query** object for this device. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type          | Mandatory| Description          |
| ------ | -------------- | ---- | -------------- |
A
Annie_wang 已提交
5487
| query  | [Query](#query) | Yes  | **Query** object to match.|
A
Annie_wang 已提交
5488 5489 5490 5491 5492

**Return value**

| Type                            | Description                                                    |
| -------------------------------- | -------------------------------------------------------- |
A
Annie_wang 已提交
5493
| Promise&lt;[Entry](#entry)[]&gt; | Promise used to return the KV pairs that match the specified **Query** object on the local device.|
A
Annie_wang 已提交
5494 5495 5496 5497 5498

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5499
| ID| **Error Message**                          |
A
Annie_wang 已提交
5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    var arr = new Uint8Array([21, 31]);
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_bool_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.BYTE_ARRAY,
                value: arr
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
5521
    console.info(`entries: {entries}`);
A
Annie_wang 已提交
5522
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
5523
        console.info('Succeeded in putting Batch');
A
Annie_wang 已提交
5524 5525 5526
        const query = new distributedKVStore.Query();
        query.prefixKey("batch_test");
        kvStore.getEntries(query).then((entries) => {
A
Annie_wang 已提交
5527
            console.info('Succeeded in getting Entries');
A
Annie_wang 已提交
5528
        }).catch((err) => {
A
Annie_wang 已提交
5529
            console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5530 5531
        });
    }).catch((err) => {
A
Annie_wang 已提交
5532
        console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`)
A
Annie_wang 已提交
5533
    });
A
Annie_wang 已提交
5534
    console.info('Succeeded in getting Entries');
A
Annie_wang 已提交
5535
} catch (e) {
A
Annie_wang 已提交
5536
    console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5537 5538 5539 5540 5541 5542 5543 5544
}
```

### getEntries

getEntries(deviceId: string, query: Query, callback: AsyncCallback&lt;Entry[]&gt;): void

Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
5545
> **NOTE**
A
Annie_wang 已提交
5546 5547 5548
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
5549 5550 5551 5552 5553 5554 5555 5556

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name  | Type                              | Mandatory| Description                                                   |
| -------- | -------------------------------------- | ---- | ------------------------------------------------------- |
| deviceId | string                                 | Yes  | ID of the target device.                                   |
A
Annie_wang 已提交
5557
| query    | [Query](#query)                         | Yes  | **Query** object to match.                                         |
A
Annie_wang 已提交
5558
| callback | AsyncCallback&lt;[Entry](#entry)[]&gt; | Yes  | Callback invoked to return the KV pairs that match the specified device ID and **Query** object.|
A
Annie_wang 已提交
5559 5560 5561 5562 5563

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5564
| ID| **Error Message**                          |
A
Annie_wang 已提交
5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    var arr = new Uint8Array([21, 31]);
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_bool_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.BYTE_ARRAY,
                value: arr
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
5586
    console.info(`entries: ${entries}`);
A
Annie_wang 已提交
5587 5588
    kvStore.putBatch(entries, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
5589
            console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5590 5591
            return;
        }
A
Annie_wang 已提交
5592
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
5593 5594 5595 5596 5597
        var query = new distributedKVStore.Query();
        query.deviceId('localDeviceId');
        query.prefixKey("batch_test");
        kvStore.getEntries('localDeviceId', query, function (err, entries) {
            if (err != undefined) {
A
Annie_wang 已提交
5598
                console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5599 5600
                return;
            }
A
Annie_wang 已提交
5601 5602 5603
            console.info('Succeeded in getting entries');
            console.info(`entries.length: ${entries.length}`);
            console.info(`entries[0]: ${entries[0]}`);
A
Annie_wang 已提交
5604 5605
        })
    });
A
Annie_wang 已提交
5606
    console.info('Succeeded in getting entries');
A
Annie_wang 已提交
5607
} catch (e) {
A
Annie_wang 已提交
5608
    console.error(`Failed to get entries.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5609 5610 5611 5612 5613 5614 5615 5616
}
```

### getEntries

getEntries(deviceId: string, query: Query): Promise&lt;Entry[]&gt;

Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result.
A
Annie_wang 已提交
5617
> **NOTE**
A
Annie_wang 已提交
5618 5619 5620
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
5621 5622 5623 5624 5625 5626 5627 5628

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name  | Type      | Mandatory| Description                |
| -------- | -------------- | ---- | -------------------- |
| deviceId | string         | Yes  | ID of the target device.|
A
Annie_wang 已提交
5629
| query    | [Query](#query) | Yes  | **Query** object to match.      |
A
Annie_wang 已提交
5630 5631 5632 5633 5634

**Return value**

| Type                            | Description                                                      |
| -------------------------------- | ---------------------------------------------------------- |
A
Annie_wang 已提交
5635
| Promise&lt;[Entry](#entry)[]&gt; | Promise used to return the KV pairs that match the specified device ID and **Query** object.|
A
Annie_wang 已提交
5636 5637 5638 5639 5640

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5641
| ID| **Error Message**                          |
A
Annie_wang 已提交
5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    var arr = new Uint8Array([21, 31]);
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_bool_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.BYTE_ARRAY,
                value: arr
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
5663
    console.info(`entries: ${entries}`);
A
Annie_wang 已提交
5664
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
5665
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
5666 5667 5668 5669
        var query = new distributedKVStore.Query();
        query.deviceId('localDeviceId');
        query.prefixKey("batch_test");
        kvStore.getEntries('localDeviceId', query).then((entries) => {
A
Annie_wang 已提交
5670
            console.info('Succeeded in getting entries');
A
Annie_wang 已提交
5671
        }).catch((err) => {
A
Annie_wang 已提交
5672
            console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5673 5674
        });
    }).catch((err) => {
A
Annie_wang 已提交
5675
        console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5676
    });
A
Annie_wang 已提交
5677
    console.info('Succeeded in getting entries');
A
Annie_wang 已提交
5678
} catch (e) {
A
Annie_wang 已提交
5679
    console.error(`Failed to get entries.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695
}
```

### getResultSet

getResultSet(keyPrefix: string, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void

Obtains a result set with the specified prefix for this device. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type                                                      | Mandatory| Description                                |
| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ |
| keyPrefix | string                                                     | Yes  | Key prefix to match.                |
A
Annie_wang 已提交
5696
| callback  | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes  | Callback invoked to return the result set with the specified prefix.|
A
Annie_wang 已提交
5697 5698 5699 5700 5701

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5702
| ID| **Error Message**                          |
A
Annie_wang 已提交
5703
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
5704
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let resultSet;
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
5727
            console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5728 5729
            return;
        }
A
Annie_wang 已提交
5730
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
5731 5732
        kvStore.getResultSet('batch_test_string_key', async function (err, result) {
            if (err != undefined) {
A
Annie_wang 已提交
5733
                console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5734 5735
                return;
            }
A
Annie_wang 已提交
5736
            console.info('Succeeded in getting result set');
A
Annie_wang 已提交
5737 5738 5739
            resultSet = result;
            kvStore.closeResultSet(resultSet, function (err, data) {
                if (err != undefined) {
A
Annie_wang 已提交
5740
                    console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5741 5742
                    return;
                }
A
Annie_wang 已提交
5743
                console.info('Succeeded in closing result set');
A
Annie_wang 已提交
5744 5745 5746 5747
            })
        });
    });
} catch (e) {
J
Jiefeng Li 已提交
5748
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769
}
```

### getResultSet

getResultSet(keyPrefix: string): Promise&lt;KVStoreResultSet&gt;

Obtains a result set with the specified prefix for this device. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name   | Type  | Mandatory| Description                |
| --------- | ------ | ---- | -------------------- |
| keyPrefix | string | Yes  | Key prefix to match.|

**Return value**

| Type                                                | Description                                   |
| ---------------------------------------------------- | --------------------------------------- |
A
Annie_wang 已提交
5770
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise used to return the result set with the specified prefix.|
A
Annie_wang 已提交
5771 5772 5773 5774 5775

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5776
| ID| **Error Message**                          |
A
Annie_wang 已提交
5777
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
5778
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let resultSet;
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
5800
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
5801
    }).catch((err) => {
A
Annie_wang 已提交
5802
        console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5803 5804
    });
    kvStore.getResultSet('batch_test_string_key').then((result) => {
A
Annie_wang 已提交
5805
        console.info('Succeeded in getting result set');
A
Annie_wang 已提交
5806 5807
        resultSet = result;
    }).catch((err) => {
A
Annie_wang 已提交
5808
        console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5809 5810
    });
    kvStore.closeResultSet(resultSet).then((err) => {
A
Annie_wang 已提交
5811
        console.info('Succeeded in closing result set');
A
Annie_wang 已提交
5812
    }).catch((err) => {
A
Annie_wang 已提交
5813
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5814 5815
    });
} catch (e) {
J
Jiefeng Li 已提交
5816
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
5817 5818 5819 5820 5821 5822 5823 5824
}
```

### getResultSet

getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void

Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
5825
> **NOTE**
A
Annie_wang 已提交
5826 5827 5828
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
5829 5830 5831 5832 5833 5834 5835 5836 5837

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name   | Type                                                    | Mandatory| Description                                                        |
| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| deviceId  | string                                                       | Yes  | ID of the target device.                                    |
| keyPrefix | string                                                       | Yes  | Key prefix to match.                                        |
A
Annie_wang 已提交
5838
| callback  | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes  | Callback invoked to return the **KvStoreResultSet** object that matches the specified device ID and key prefix.|
A
Annie_wang 已提交
5839 5840 5841 5842 5843

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5844
| ID| **Error Message**                          |
A
Annie_wang 已提交
5845
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
5846
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
5847 5848 5849 5850 5851 5852 5853 5854 5855 5856
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let resultSet;
    kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) {
        if (err != undefined) {
A
Annie_wang 已提交
5857
            console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5858 5859
            return;
        }
A
Annie_wang 已提交
5860
        console.info('Succeeded in getting resultSet');
A
Annie_wang 已提交
5861 5862 5863
        resultSet = result;
        kvStore.closeResultSet(resultSet, function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
5864
                console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5865 5866
                return;
            }
A
Annie_wang 已提交
5867
            console.info('Succeeded in closing resultSet');
A
Annie_wang 已提交
5868 5869 5870
        })
    });
} catch (e) {
A
Annie_wang 已提交
5871
    console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5872 5873 5874 5875 5876 5877 5878 5879
}
```

### getResultSet

getResultSet(deviceId: string, keyPrefix: string): Promise&lt;KVStoreResultSet&gt;

Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result.
A
Annie_wang 已提交
5880
> **NOTE**
A
Annie_wang 已提交
5881 5882 5883
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name   | Type| Mandatory| Description                    |
| --------- | -------- | ---- | ------------------------ |
| deviceId  | string   | Yes  | ID of the target device.|
| keyPrefix | string   | Yes  | Key prefix to match.    |

**Return value**

| Type                                                  | Description                                                        |
| ------------------------------------------------------ | ------------------------------------------------------------ |
A
Annie_wang 已提交
5898
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise used to return the **KvStoreResultSet** object that matches the specified device ID and key prefix.|
A
Annie_wang 已提交
5899 5900 5901 5902 5903

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5904
| ID| **Error Message**                          |
A
Annie_wang 已提交
5905
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
5906
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
5907 5908 5909 5910 5911 5912 5913 5914 5915
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let resultSet;
    kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => {
A
Annie_wang 已提交
5916
        console.info('Succeeded in getting resultSet');
A
Annie_wang 已提交
5917 5918
        resultSet = result;
    }).catch((err) => {
A
Annie_wang 已提交
5919
        console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5920 5921
    });
    kvStore.closeResultSet(resultSet).then((err) => {
A
Annie_wang 已提交
5922
        console.info('Succeeded in closing resultSet');
A
Annie_wang 已提交
5923
    }).catch((err) => {
A
Annie_wang 已提交
5924
        console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5925 5926
    });
} catch (e) {
A
Annie_wang 已提交
5927
    console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
5928 5929 5930 5931 5932 5933 5934 5935
}
```

### getResultSet

getResultSet(deviceId: string, query: Query, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void

Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
5936
> **NOTE**
A
Annie_wang 已提交
5937 5938 5939
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
5940 5941 5942 5943 5944 5945 5946 5947

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name  | Type                                                    | Mandatory| Description                                                        |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| deviceId | string                                                       | Yes  | ID of the device to which the **KVStoreResultSet** object belongs.                          |
A
Annie_wang 已提交
5948
| query    | [Query](#query)                                               | Yes  | **Query** object to match.                                              |
A
Annie_wang 已提交
5949
| callback | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes  | Callback invoked to return the **KvStoreResultSet** object that matches the specified device ID and **Query** object.|
A
Annie_wang 已提交
5950 5951 5952 5953 5954

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
5955
| ID| **Error Message**                          |
A
Annie_wang 已提交
5956
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
5957
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let resultSet;
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
5980
            console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5981 5982
            return;
        }
A
Annie_wang 已提交
5983
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
5984 5985 5986 5987
        const query = new distributedKVStore.Query();
        query.prefixKey("batch_test");
        kvStore.getResultSet('localDeviceId', query, async function (err, result) {
            if (err != undefined) {
A
Annie_wang 已提交
5988
                console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5989 5990
                return;
            }
A
Annie_wang 已提交
5991
            console.info('Succeeded in getting resultSet');
A
Annie_wang 已提交
5992 5993 5994
            resultSet = result;
            kvStore.closeResultSet(resultSet, function (err, data) {
                if (err != undefined) {
A
Annie_wang 已提交
5995
                    console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
5996 5997
                    return;
                }
A
Annie_wang 已提交
5998
                console.info('Succeeded in closing resultSet');
A
Annie_wang 已提交
5999 6000 6001 6002
            })
        });
    });
} catch (e) {
A
Annie_wang 已提交
6003
    console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
6004 6005 6006 6007 6008 6009 6010 6011
}
```

### getResultSet

getResultSet(deviceId: string, query: Query): Promise&lt;KVStoreResultSet&gt;

Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result.
A
Annie_wang 已提交
6012
> **NOTE**
A
Annie_wang 已提交
6013 6014 6015
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
6016 6017 6018 6019 6020 6021 6022 6023

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name  | Type      | Mandatory| Description                              |
| -------- | -------------- | ---- | ---------------------------------- |
| deviceId | string         | Yes  | ID of the device to which the **KVStoreResultSet** object belongs.|
A
Annie_wang 已提交
6024
| query    | [Query](#query) | Yes  | **Query** object to match.                    |
A
Annie_wang 已提交
6025 6026 6027 6028 6029

**Return value**

| Type                                                  | Description                                                        |
| ------------------------------------------------------ | ------------------------------------------------------------ |
A
Annie_wang 已提交
6030
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise used to return the **KvStoreResultSet** object that matches the specified device ID and **Query** object.|
A
Annie_wang 已提交
6031 6032 6033 6034 6035

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
6036
| ID| **Error Message**                          |
A
Annie_wang 已提交
6037
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
6038
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let resultSet;
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
6060
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
6061
    }).catch((err) => {
A
Annie_wang 已提交
6062
        console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6063 6064 6065 6066
    });
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    kvStore.getResultSet('localDeviceId', query).then((result) => {
A
Annie_wang 已提交
6067
        console.info('Succeeded in getting resultSet');
A
Annie_wang 已提交
6068 6069
        resultSet = result;
    }).catch((err) => {
A
Annie_wang 已提交
6070
        console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6071 6072
    });
    query.deviceId('localDeviceId');
A
Annie_wang 已提交
6073
    console.info("GetResultSet " + query.getSqlLike());
A
Annie_wang 已提交
6074
    kvStore.closeResultSet(resultSet).then((err) => {
A
Annie_wang 已提交
6075
        console.info('Succeeded in closing resultSet');
A
Annie_wang 已提交
6076
    }).catch((err) => {
A
Annie_wang 已提交
6077
        console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6078 6079 6080
    });

} catch (e) {
A
Annie_wang 已提交
6081
    console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096
}
```

### getResultSet

getResultSet(query: Query): Promise&lt;KVStoreResultSet&gt;

Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type          | Mandatory| Description          |
| ------ | -------------- | ---- | -------------- |
A
Annie_wang 已提交
6097
| query  | [Query](#query) | Yes  | **Query** object to match.|
A
Annie_wang 已提交
6098 6099 6100 6101 6102

**Return value**

| Type                                                | Description                                                        |
| ---------------------------------------------------- | ------------------------------------------------------------ |
A
Annie_wang 已提交
6103
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise used to return the **KVStoreResultSet** object obtained.|
A
Annie_wang 已提交
6104 6105 6106 6107 6108

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
6109
| ID| **Error Message**                          |
A
Annie_wang 已提交
6110
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
6111
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let resultSet;
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
6133
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
6134
    }).catch((err) => {
A
Annie_wang 已提交
6135
        console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6136 6137 6138 6139
    });
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    kvStore.getResultSet(query).then((result) => {
A
Annie_wang 已提交
6140
        console.info('Succeeded in getting result set');
A
Annie_wang 已提交
6141 6142
        resultSet = result;
    }).catch((err) => {
A
Annie_wang 已提交
6143
        console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6144 6145
    });
} catch (e) {
J
Jiefeng Li 已提交
6146
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
6147 6148 6149 6150 6151
}    
```

### getResultSet

A
Annie_wang 已提交
6152
getResultSet(query: Query, callback:AsyncCallback&lt;KVStoreResultSet&gt;): void
A
Annie_wang 已提交
6153

A
Annie_wang 已提交
6154
Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
6155
> **NOTE**
A
Annie_wang 已提交
6156 6157 6158
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
6159

A
Annie_wang 已提交
6160
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
A
Annie_wang 已提交
6161 6162 6163 6164 6165

**Parameters**

| Name  | Type          | Mandatory| Description                              |
| -------- | -------------- | ---- | ---------------------------------- |
A
Annie_wang 已提交
6166
| query    | [Query](#query) | Yes  | **Query** object to match.                    |
A
Annie_wang 已提交
6167
| callback    | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Yes  | Callback invoked to return the **KVStoreResultSet** object obtained.        |
A
Annie_wang 已提交
6168 6169 6170 6171 6172 6173


**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
6174
| ID| **Error Message**                          |
A
Annie_wang 已提交
6175
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
6176
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let resultSet;
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
A
Annie_wang 已提交
6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219
    kvStore.putBatch(entries, async function (err, data) {
        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");
        kvStore.getResultSet(query, async function (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;
            kvStore.closeResultSet(resultSet, function (err, data) {
                if (err != undefined) {
                    console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`);
                    return;
                }
                console.info('Succeeded in closing resultSet');
            })
        });
A
Annie_wang 已提交
6220 6221
    });
} catch (e) {
A
Annie_wang 已提交
6222
    console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239
}
```

### getResultSet

getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void

Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses an asynchronous callback to return the result.

**System API**: This is a system API.

**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider

**Parameters**

| Name    | Type                                                        | Mandatory| Description                                                        |
| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
A
Annie_wang 已提交
6240
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes  | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.             |
A
Annie_wang 已提交
6241 6242 6243 6244 6245 6246
| callback   | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt;   | Yes  | Callback invoked to return the **KVStoreResultSet** object obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
6247
| ID| **Error Message**                          |
A
Annie_wang 已提交
6248
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
6249
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';

try {
    let resultSet;
    let predicates = new dataSharePredicates.DataSharePredicates();
    predicates.prefixKey("batch_test_string_key");
    kvStore.getResultSet(predicates, async function (err, result) {
        if (err != undefined) {
A
Annie_wang 已提交
6264
            console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6265 6266
            return;
        }
A
Annie_wang 已提交
6267
        console.info('Succeeded in getting result set');
A
Annie_wang 已提交
6268 6269 6270
        resultSet = result;
        kvStore.closeResultSet(resultSet, function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
6271
                console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6272 6273
                return;
            }
A
Annie_wang 已提交
6274
            console.info('Succeeded in closing result set');
A
Annie_wang 已提交
6275 6276 6277
        })
    });
} catch (e) {
J
Jiefeng Li 已提交
6278
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295
}
```

### getResultSet

getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise&lt;KVStoreResultSet&gt;

Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses a promise to return the result.

**System API**: This is a system API.

**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider

**Parameters**

| Name    | Type                                                        | Mandatory| Description                                           |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- |
A
Annie_wang 已提交
6296
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes  | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.|
A
Annie_wang 已提交
6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307

**Return value**

| Type                                                | Description                     |
| ---------------------------------------------------- | ------------------------- |
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
6308
| ID| **Error Message**                          |
A
Annie_wang 已提交
6309
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
6310
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';

try {
    let resultSet;
    let predicates = new dataSharePredicates.DataSharePredicates();
    predicates.prefixKey("batch_test_string_key");
    kvStore.getResultSet(predicates).then((result) => {
A
Annie_wang 已提交
6324
        console.info('Succeeded in getting result set');
A
Annie_wang 已提交
6325 6326
        resultSet = result;
    }).catch((err) => {
A
Annie_wang 已提交
6327
        console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6328 6329
    });
    kvStore.closeResultSet(resultSet).then((err) => {
A
Annie_wang 已提交
6330
        console.info('Succeeded in closing result set');
A
Annie_wang 已提交
6331
    }).catch((err) => {
A
Annie_wang 已提交
6332
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6333 6334
    });
} catch (e) {
J
Jiefeng Li 已提交
6335
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
6336 6337 6338 6339 6340 6341 6342 6343
}
```

### getResultSet

getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;KVStoreResultSet&gt;): void

Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
6344
> **NOTE**
A
Annie_wang 已提交
6345 6346 6347
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364

**System API**: This is a system API.

**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider

**Parameters**

| Name    | Type                                                    | Mandatory| Description                                                        |
| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| deviceId  | string                                                       | Yes  | ID of the target device.                                    |
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes  | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.             |
| callback   | AsyncCallback&lt;[KVStoreResultSet](#kvstoreresultset)&gt;   | Yes  | Callback invoked to return the **KVStoreResultSet** object obtained.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
6365
| ID| **Error Message**                          |
A
Annie_wang 已提交
6366
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
6367
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';

try {
    let resultSet;
    let predicates = new dataSharePredicates.DataSharePredicates();
    predicates.prefixKey("batch_test_string_key");
    kvStore.getResultSet('localDeviceId', predicates, async function (err, result) {
        if (err != undefined) {
A
Annie_wang 已提交
6382
            console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6383 6384
            return;
        }
A
Annie_wang 已提交
6385
        console.info('Succeeded in getting result set');
A
Annie_wang 已提交
6386 6387 6388
        resultSet = result;
        kvStore.closeResultSet(resultSet, function (err, data) {
            if (err != undefined) {
A
Annie_wang 已提交
6389
                console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6390 6391
                return;
            }
A
Annie_wang 已提交
6392
            console.info('Succeeded in closing result set');
A
Annie_wang 已提交
6393 6394 6395
        })
    });
} catch (e) {
J
Jiefeng Li 已提交
6396
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
6397 6398 6399 6400 6401 6402 6403 6404
}
```

### getResultSet

getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise&lt;KVStoreResultSet&gt;

Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result.
A
Annie_wang 已提交
6405
> **NOTE**
A
Annie_wang 已提交
6406 6407 6408
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
6409 6410 6411 6412 6413 6414 6415 6416 6417 6418

**System API**: This is a system API.

**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider

**Parameters**

| Name    | Type                                                    | Mandatory| Description                                           |
| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- |
| deviceId  | string                                                       | Yes  | ID of the target device.                                    |
A
Annie_wang 已提交
6419
| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes  | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.|
A
Annie_wang 已提交
6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430

**Return value**

| Type                                                | Description                     |
| ---------------------------------------------------- | ------------------------- |
| Promise&lt;[KVStoreResultSet](#kvstoreresultset)&gt; | Promise that returns no value.|

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
6431
| ID| **Error Message**                          |
A
Annie_wang 已提交
6432
| ------------ | -------------------------------------- |
A
Annie_wang 已提交
6433
| 15100001     | Over max limits.                      |
A
Annie_wang 已提交
6434 6435 6436 6437 6438 6439 6440
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
import dataSharePredicates from '@ohos.data.dataSharePredicates';
A
Annie_wang 已提交
6441

A
Annie_wang 已提交
6442 6443 6444 6445 6446
try {
    let resultSet;
    let predicates = new dataSharePredicates.DataSharePredicates();
    predicates.prefixKey("batch_test_string_key");
    kvStore.getResultSet('localDeviceId', predicates).then((result) => {
A
Annie_wang 已提交
6447
        console.info('Succeeded in getting result set');
A
Annie_wang 已提交
6448 6449
        resultSet = result;
    }).catch((err) => {
A
Annie_wang 已提交
6450
        console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6451 6452
    });
    kvStore.closeResultSet(resultSet).then((err) => {
A
Annie_wang 已提交
6453
        console.info('Succeeded in closing result set');
A
Annie_wang 已提交
6454
    }).catch((err) => {
A
Annie_wang 已提交
6455
        console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6456 6457
    });
} catch (e) {
J
Jiefeng Li 已提交
6458
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473
}
```

### getResultSize

getResultSize(query: Query, callback: AsyncCallback&lt;number&gt;): void

Obtains the number of results that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name  | Type                       | Mandatory| Description                                             |
| -------- | --------------------------- | ---- | ------------------------------------------------- |
A
Annie_wang 已提交
6474
| query    | [Query](#query)              | Yes  | **Query** object to match.                                   |
A
Annie_wang 已提交
6475
| callback | AsyncCallback&lt;number&gt; | Yes  | Callback invoked to return the number of results obtained.|
A
Annie_wang 已提交
6476 6477 6478 6479 6480

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
6481
| ID| **Error Message**                          |
A
Annie_wang 已提交
6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries, async function (err, data) {
A
Annie_wang 已提交
6503
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
6504 6505 6506 6507
        const query = new distributedKVStore.Query();
        query.prefixKey("batch_test");
        kvStore.getResultSize(query, async function (err, resultSize) {
            if (err != undefined) {
A
Annie_wang 已提交
6508
                console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6509 6510
                return;
            }
A
Annie_wang 已提交
6511
            console.info('Succeeded in getting result set size');
A
Annie_wang 已提交
6512 6513 6514
        });
    });
} catch (e) {
J
Jiefeng Li 已提交
6515
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530
}
```

### getResultSize

getResultSize(query: Query): Promise&lt;number&gt;

Obtains the number of results that match the specified **Query** object for this device. This API uses a promise to return the result.

**System capability**: SystemCapability.DistributedDataManager.KVStore.Core

**Parameters**

| Name| Type          | Mandatory| Description          |
| ------ | -------------- | ---- | -------------- |
A
Annie_wang 已提交
6531
| query  | [Query](#query) | Yes  | **Query** object to match.|
A
Annie_wang 已提交
6532 6533 6534 6535 6536

**Return value**

| Type                 | Description                                                |
| --------------------- | ---------------------------------------------------- |
A
Annie_wang 已提交
6537
| Promise&lt;number&gt; | Promise used to return the number of results obtained.|
A
Annie_wang 已提交
6538 6539 6540 6541 6542

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
6543
| ID| **Error Message**                          |
A
Annie_wang 已提交
6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
6565
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
6566
    }).catch((err) => {
A
Annie_wang 已提交
6567
        console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6568 6569 6570 6571
    });
    const query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    kvStore.getResultSize(query).then((resultSize) => {
A
Annie_wang 已提交
6572
        console.info('Succeeded in getting result set size');
A
Annie_wang 已提交
6573
    }).catch((err) => {
A
Annie_wang 已提交
6574
        console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6575 6576
    });
} catch (e) {
J
Jiefeng Li 已提交
6577
    console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`);
A
Annie_wang 已提交
6578 6579 6580 6581 6582 6583 6584 6585
}
```

### getResultSize

getResultSize(deviceId: string, query: Query, callback: AsyncCallback&lt;number&gt;): void;

Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result.
A
Annie_wang 已提交
6586
> **NOTE**
A
Annie_wang 已提交
6587 6588 6589
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
6590 6591 6592 6593 6594 6595 6596 6597

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name  | Type                   | Mandatory| Description                                               |
| -------- | --------------------------- | ---- | --------------------------------------------------- |
| deviceId | string                      | Yes  | ID of the device to which the **KVStoreResultSet** object belongs.                 |
A
Annie_wang 已提交
6598
| query    | [Query](#query)              | Yes  | **Query** object to match.                                     |
A
Annie_wang 已提交
6599
| callback | AsyncCallback&lt;number&gt; | Yes  | Callback invoked to return the number of results obtained. |
A
Annie_wang 已提交
6600 6601 6602 6603 6604

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
6605
| ID| **Error Message**                          |
A
Annie_wang 已提交
6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries, async function (err, data) {
        if (err != undefined) {
A
Annie_wang 已提交
6628
            console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6629 6630
            return;
        }
A
Annie_wang 已提交
6631
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
6632 6633 6634 6635
        const query = new distributedKVStore.Query();
        query.prefixKey("batch_test");
        kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) {
            if (err != undefined) {
A
Annie_wang 已提交
6636
                console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6637 6638
                return;
            }
A
Annie_wang 已提交
6639
            console.info('Succeeded in getting resultSize');
A
Annie_wang 已提交
6640 6641 6642 6643
            ;
        });
    });
} catch (e) {
A
Annie_wang 已提交
6644
    console.error(`Failed to get resultSize.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
6645 6646 6647 6648 6649 6650 6651 6652
}
```

### getResultSize

getResultSize(deviceId: string, query: Query): Promise&lt;number&gt;

Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result.
A
Annie_wang 已提交
6653
> **NOTE**
A
Annie_wang 已提交
6654 6655 6656
>
> **deviceId** is obtained by [deviceManager.getTrustedDeviceListSync](js-apis-device-manager.md#gettrusteddevicelistsync). The APIs of the **deviceManager** module are system interfaces and available only to system applications.
> For details about how to obtain **deviceId**, see [sync()](#sync).
A
Annie_wang 已提交
6657 6658 6659 6660 6661 6662 6663 6664

**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore

**Parameters**

| Name  | Type      | Mandatory| Description                              |
| -------- | -------------- | ---- | ---------------------------------- |
| deviceId | string         | Yes  | ID of the device to which the **KVStoreResultSet** object belongs.|
A
Annie_wang 已提交
6665
| query    | [Query](#query) | Yes  | **Query** object to match.                    |
A
Annie_wang 已提交
6666 6667 6668 6669 6670

**Return value**

| Type                 | Description                                                  |
| --------------------- | ------------------------------------------------------ |
A
Annie_wang 已提交
6671
| Promise&lt;number&gt; | Promise used to return the number of results obtained. |
A
Annie_wang 已提交
6672 6673 6674 6675 6676

**Error codes**

For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md).

A
Annie_wang 已提交
6677
| ID| **Error Message**                          |
A
Annie_wang 已提交
6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698
| ------------ | -------------------------------------- |
| 15100003     | Database corrupted.                    |
| 15100005     | Database or result set already closed. |

**Example**

```js
try {
    let entries = [];
    for (var i = 0; i < 10; i++) {
        var key = 'batch_test_string_key';
        var entry = {
            key: key + i,
            value: {
                type: distributedKVStore.ValueType.STRING,
                value: 'batch_test_string_value'
            }
        }
        entries.push(entry);
    }
    kvStore.putBatch(entries).then(async (err) => {
A
Annie_wang 已提交
6699
        console.info('Succeeded in putting batch');
A
Annie_wang 已提交
6700
    }).catch((err) => {
A
Annie_wang 已提交
6701
        console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6702 6703 6704 6705
    });
    var query = new distributedKVStore.Query();
    query.prefixKey("batch_test");
    kvStore.getResultSize('localDeviceId', query).then((resultSize) => {
A
Annie_wang 已提交
6706
        console.info('Succeeded in getting resultSize');
A
Annie_wang 已提交
6707 6708
        ;
    }).catch((err) => {
A
Annie_wang 已提交
6709
        console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`);
A
Annie_wang 已提交
6710 6711
    });
} catch (e) {
A
Annie_wang 已提交
6712
    console.error(`Failed to get resultSize.code is ${e.code},message is ${e.message}`);
A
Annie_wang 已提交
6713 6714
}
```