1# @ohos.data.distributedKVStore (Distributed KV Store) 2 3The **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. 4 5The **distributedKVStore** module provides the following functions: 6 7- [KVManager](#kvmanager): provides a **KVManager** instance to obtain KV store information. 8- [KVStoreResultSet](#kvstoreresultset): provides APIs for accessing the results obtained from a KV store. 9- [Query](#query): provides APIs for setting predicates for data query. 10- [SingleKVStore](#singlekvstore): provides APIs for querying and synchronizing data in single KV stores. The single KV stores manage data without distinguishing devices. 11- [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. 12 13> **NOTE** 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. 16> - All the APIs that need to obtain **deviceId** in this module are available only to system applications. 17 18## Modules to Import 19 20```js 21import distributedKVStore from '@ohos.data.distributedKVStore'; 22``` 23 24## KVManagerConfig 25 26Provides the **KVManager** instance configuration, including the bundle name of the invoker and the application context. 27 28**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 29 30| Name | Type | Mandatory| Description | 31| ---------- | --------------------- | ---- | ------------------------------------------------------------ | 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).| 33| bundleName | string | Yes | Bundle name. | 34 35## Constants 36 37Provides constants of the distributed KV store. 38 39**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 40 41| Name | Value | Description | 42| --------------------- | ------- | --------------------------------------- | 43| MAX_KEY_LENGTH | 1024 | Maximum length of a key in a distributed KV store, in bytes. | 44| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in a distributed KV store, in bytes. | 45| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a key in a device KV store, in bytes.| 46| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. | 47| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes. | 48| MAX_BATCH_SIZE | 128 | Maximum number of batch operations. | 49 50## ValueType 51 52Enumerates the types of the value in a KV pair. 53 54**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 55 56| Name | Description | 57| ---------- | ---------------------- | 58| STRING | String. | 59| INTEGER | Integer. | 60| FLOAT | Float (single-precision floating point). | 61| BYTE_ARRAY | Byte array.| 62| BOOLEAN | Boolean. | 63| DOUBLE | Double (double-precision floating point).| 64 65## Value 66 67Defines the **value** object in a KV store. 68 69**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 70 71| Name | Type |Mandatory | Description | 72| ----- | ------- |-----|------------------------ | 73| type | [ValueType](#valuetype) | Yes|Type of the value. | 74| value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair. | 75 76## Entry 77 78Defines the KV pairs stored in a KV store. 79 80**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 81 82| Name | Type | Mandatory| Description | 83| ----- | --------------- | ---- | -------- | 84| key | string | Yes | Key of a KV pair in the KV store. | 85| value | [Value](#value) | Yes | Value of a KV pair in the KV store. | 86 87## ChangeNotification 88 89Defines the content of a data change notification, including inserted data, updated data, deleted data, and device ID. 90 91**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 92 93| Name | Type | Mandatory | Description | 94| ------------- | ----------------- | ---- | ------------------------ | 95| insertEntries | [Entry](#entry)[] | Yes | Data inserted. | 96| updateEntries | [Entry](#entry)[] | Yes | Data updated. | 97| deleteEntries | [Entry](#entry)[] | Yes | Data deleted. | 98| deviceId | string | Yes | UUID of the device.| 99 100## SyncMode 101 102Enumerates the synchronization modes. 103 104**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 105 106| Name | Description | 107| --------- | ---------------------------------------------------- | 108| PULL_ONLY | Pull data from the peer end to the local end only. | 109| PUSH_ONLY | Push data from the local end to the peer end only. | 110| PUSH_PULL | Push data from the local end to the peer end and then pull data from the peer end to the local end.| 111 112## SubscribeType 113 114Enumerates the subscription types. 115 116**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 117 118| Name | Description | 119| --------------------- | ---------------------------- | 120| SUBSCRIBE_TYPE_LOCAL | Local data changes. | 121| SUBSCRIBE_TYPE_REMOTE | Remote data changes. | 122| SUBSCRIBE_TYPE_ALL | Local and remote data changes.| 123 124## KVStoreType 125 126Enumerates the distributed KV store types. 127 128| Name | Description | 129| -------------------- | ------------------------------------------------------------ | 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| 131| SINGLE_VERSION | Single KV store.<br> The single KV store does not differentiate data by device. If the same key is modified by different devices, the data will be overwritten.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 132 133## SecurityLevel 134 135Enumerates the KV store security levels. 136 137**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 138 139| Name | Description | 140| -------: | ------------------------------------------------------------ | 141| S1 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.| 142| S2 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.| 143| S3 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.| 144| S4 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.| 145 146## Options 147 148Provides KV store configuration. 149 150| Name | Type | Mandatory| Description | 151| --------------- | -------------- | ---- | -------------------------| 152| createIfMissing | boolean | No | Whether to create a KV store if no database file exists. The default value is **true**, which means to create a KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 153| encrypt | boolean | No | Whether to encrypt the KV store. The default value is **false**, which means the KV store is not encrypted.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 154| backup | boolean | No | Whether to back up the KV store. The default value is **true**, which means to back up the KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 155| autoSync | boolean | No | Whether to automatically synchronize database files. The default value is **false**, which means the database files are manually synchronized.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core<br>**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC| 156| kvStoreType | [KVStoreType](#kvstoretype) | No | Type of the KV store to create. The default value is **DEVICE_COLLABORATION**, which indicates a device KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 157| securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 158| schema | [Schema](#schema) | No | Schema used to define the values stored in the KV store. The default value is **undefined**, which means no schema is set.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| 159 160## Schema 161 162Defines 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. 163 164**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 165 166| Name | Type | Readable| Writable| Description | 167| ------- | ----------------------- | ---- | ---- | -------------------------- | 168| root | [FieldNode](#fieldnode) | Yes | Yes | JSON root object. | 169| indexes | Array\<string> | Yes | Yes | String array in JSON format.| 170| mode | number | Yes | Yes | Schema mode. | 171| skip | number | Yes | Yes | Size of a skip of the schema. | 172 173### constructor 174 175constructor() 176 177A constructor used to create a **Schema** instance. 178 179**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 180 181## FieldNode 182 183Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store. 184 185**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 186 187| Name | Type | Readable| Writable| Description | 188| -------- | ------- | ---- | ---- | ------------------------------ | 189| nullable | boolean | Yes | Yes | Whether the database field can be null. | 190| default | string | Yes | Yes | Default value of a **FieldNode**. | 191| type | number | Yes | Yes | Value of the data type corresponding to the specified node.| 192 193### constructor 194 195constructor(name: string) 196 197A constructor used to create a **FieldNode** instance with a string field. 198 199**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 200 201**Parameters** 202 203| Name| Type| Mandatory| Description | 204| ------ | -------- | ---- | --------------- | 205| name | string | Yes | Value of **FieldNode**.| 206 207### appendChild 208 209appendChild(child: FieldNode): boolean 210 211Appends a child node to this **FieldNode**. 212 213**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 214 215**Parameters** 216 217| Name| Type | Mandatory| Description | 218| ------ | ----------------------- | ---- | ---------------- | 219| child | [FieldNode](#fieldnode) | Yes | Child node to append.| 220 221**Return value** 222 223| Type | Description | 224| ------- | ------------------------------------------------------------ | 225| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 226 227**Example** 228 229```js 230import distributedKVStore from '@ohos.data.distributedKVStore'; 231 232try { 233 let node = new distributedKVStore.FieldNode("root"); 234 let child1 = new distributedKVStore.FieldNode("child1"); 235 let child2 = new distributedKVStore.FieldNode("child2"); 236 let child3 = new distributedKVStore.FieldNode("child3"); 237 node.appendChild(child1); 238 node.appendChild(child2); 239 node.appendChild(child3); 240 console.info("appendNode " + JSON.stringify(node)); 241 child1 = null; 242 child2 = null; 243 child3 = null; 244 node = null; 245} catch (e) { 246 console.error("AppendChild " + e); 247} 248``` 249 250## distributedKVStore.createKVManager 251 252createKVManager(config: KVManagerConfig): KVManager 253 254Creates a **KVManager** instance for KV store management. 255 256**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 257 258**Parameters** 259 260| Name| Type | Mandatory| Description | 261| ------ | ----------------------------- | ---- | --------------------------------------------------------- | 262| config | [KVManagerConfig](#kvmanagerconfig) | Yes | **KVManager** instance configuration, including the bundle name and user information of the caller.| 263 264**Return value** 265 266| Type | Description | 267| -------------------------------------- | ------------------------------------------ | 268| [KVManager](#kvmanager) | **KVManager** instance created.| 269 270**Example** 271 272Stage model: 273 274```js 275import UIAbility from '@ohos.app.ability.UIAbility'; 276 277let kvManager; 278export default class EntryAbility extends UIAbility { 279 onCreate() { 280 console.info("MyAbilityStage onCreate") 281 let context = this.context 282 const kvManagerConfig = { 283 context: context, 284 bundleName: 'com.example.datamanagertest', 285 } 286 try { 287 kvManager = distributedKVStore.createKVManager(kvManagerConfig); 288 console.info("Succeeded in creating KVManager"); 289 } catch (e) { 290 console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); 291 } 292 } 293} 294``` 295 296FA model: 297 298```js 299import featureAbility from '@ohos.ability.featureAbility'; 300let kvManager; 301let context = featureAbility.getContext() 302const kvManagerConfig = { 303 context: context, 304 bundleName: 'com.example.datamanagertest', 305} 306try { 307 kvManager = distributedKVStore.createKVManager(kvManagerConfig); 308 console.info("Succeeded in creating KVManager"); 309} catch (e) { 310 console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); 311} 312``` 313 314## KVManager 315 316Provides 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. 317 318### getKVStore 319 320getKVStore<T>(storeId: string, options: Options, callback: AsyncCallback<T>): void 321 322Creates and obtains a distributed KV store. This API uses an asynchronous callback to return the result. 323 324**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 325 326**Parameters** 327 328| Name | Type | Mandatory| Description | 329| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 330| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 331| options | [Options](#options) | Yes | Configuration of the KV store to create. | 332| callback | AsyncCallback<T> | Yes | Callback invoked to return the **SingleKVStore** or **DeviceKVStore** instance created.| 333 334**Error codes** 335 336For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 337 338| ID| **Error Message** | 339| ------------ | ------------------------------------------- | 340| 15100002 | Open existed database with changed options. | 341| 15100003 | Database corrupted. | 342 343**Example** 344 345```js 346let kvStore; 347let kvManager; 348try { 349 const options = { 350 createIfMissing: true, 351 encrypt: false, 352 backup: false, 353 autoSync: true, 354 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 355 securityLevel: distributedKVStore.SecurityLevel.S2, 356 }; 357 kvManager.getKVStore('storeId', options, function (err, store) { 358 if (err) { 359 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 360 return; 361 } 362 console.info("Succeeded in getting KVStore"); 363 kvStore = store; 364 }); 365} catch (e) { 366 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 367} 368``` 369 370### getKVStore 371 372getKVStore<T>(storeId: string, options: Options): Promise<T> 373 374Creates and obtains a distributed KV store. This API uses a promise to return the result. 375 376**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 377 378**Parameters** 379 380| Name | Type | Mandatory| Description | 381| ------- | ------------------- | ---- | ------------------------------------------------------------ | 382| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 383| options | [Options](#options) | Yes | Configuration of the distributed KV store to create. | 384 385**Return value** 386 387| Type | Description | 388| ---------------- | ------------------------------------------------------------ | 389| Promise<T> | Promise used to return the **SingleKVStore** or **DeviceKVStore** instance created.| 390 391**Error codes** 392 393For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 394 395| ID| **Error Message** | 396| ------------ | ------------------------------------------- | 397| 15100002 | Open existed database with changed options. | 398| 15100003 | Database corrupted. | 399 400**Example** 401 402```js 403let kvStore; 404let kvManager; 405try { 406 const options = { 407 createIfMissing: true, 408 encrypt: false, 409 backup: false, 410 autoSync: true, 411 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 412 securityLevel: distributedKVStore.SecurityLevel.S2, 413 }; 414 kvManager.getKVStore('storeId', options).then((store) => { 415 console.info("Succeeded in getting KVStore"); 416 kvStore = store; 417 }).catch((err) => { 418 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 419 }); 420} catch (e) { 421 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 422} 423``` 424 425### closeKVStore 426 427closeKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void 428 429Closes a distributed KV store. This API uses an asynchronous callback to return the result. 430 431**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 432 433**Parameters** 434 435| Name | Type | Mandatory| Description | 436| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 437| appId | string | Yes | Bundle name of the app that invokes the KV store. | 438| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 439| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 440 441**Example** 442 443```js 444let kvStore; 445let kvManager; 446const options = { 447 createIfMissing: true, 448 encrypt: false, 449 backup: false, 450 autoSync: true, 451 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 452 schema: undefined, 453 securityLevel: distributedKVStore.SecurityLevel.S2, 454} 455try { 456 kvManager.getKVStore('storeId', options, async function (err, store) { 457 if (err != undefined) { 458 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 459 return; 460 } 461 console.info('Succeeded in getting KVStore'); 462 kvStore = store; 463 kvStore = null; 464 store = null; 465 kvManager.closeKVStore('appId', 'storeId', function (err) { 466 if (err != undefined) { 467 console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`); 468 return; 469 } 470 console.info('Succeeded in closing KVStore'); 471 }); 472 }); 473} catch (e) { 474 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 475} 476``` 477 478### closeKVStore 479 480closeKVStore(appId: string, storeId: string): Promise<void> 481 482Closes a distributed KV store. This API uses a promise to return the result. 483 484**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 485 486**Parameters** 487 488| Name | Type| Mandatory| Description | 489| ------- | -------- | ---- | ------------------------------------------------------------ | 490| appId | string | Yes | Bundle name of the app that invokes the KV store. | 491| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 492 493**Return value** 494 495| Type | Description | 496| -------------- | ------------------------- | 497| Promise\<void> | Promise that returns no value.| 498 499**Example** 500 501```js 502let kvManager; 503let kvStore; 504const options = { 505 createIfMissing: true, 506 encrypt: false, 507 backup: false, 508 autoSync: true, 509 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 510 schema: undefined, 511 securityLevel: distributedKVStore.SecurityLevel.S2, 512} 513try { 514 kvManager.getKVStore('storeId', options).then(async (store) => { 515 console.info('Succeeded in getting KVStore'); 516 kvStore = store; 517 kvStore = null; 518 store = null; 519 kvManager.closeKVStore('appId', 'storeId').then(() => { 520 console.info('Succeeded in closing KVStore'); 521 }).catch((err) => { 522 console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`); 523 }); 524 }).catch((err) => { 525 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 526 }); 527} catch (e) { 528 console.error(`Failed to close KVStore.code is ${e.code},message is ${e.message}`); 529} 530``` 531 532### deleteKVStore 533 534deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void 535 536Deletes a distributed KV store. This API uses an asynchronous callback to return the result. 537 538**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 539 540**Parameters** 541 542| Name | Type | Mandatory| Description | 543| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 544| appId | string | Yes | Bundle name of the app that invokes the KV store. | 545| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 546| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 547 548**Error codes** 549 550For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 551 552| ID| **Error Message**| 553| ------------ | ------------ | 554| 15100004 | Not found. | 555 556**Example** 557 558```js 559let kvManager; 560let kvStore; 561const options = { 562 createIfMissing: true, 563 encrypt: false, 564 backup: false, 565 autoSync: true, 566 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 567 schema: undefined, 568 securityLevel: distributedKVStore.SecurityLevel.S2, 569} 570try { 571 kvManager.getKVStore('store', options, async function (err, store) { 572 if (err != undefined) { 573 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 574 return; 575 } 576 console.info('Succeeded in getting KVStore'); 577 kvStore = store; 578 kvStore = null; 579 store = null; 580 kvManager.deleteKVStore('appId', 'storeId', function (err) { 581 if (err != undefined) { 582 console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`); 583 return; 584 } 585 console.info(`Succeeded in deleting KVStore`); 586 }); 587 }); 588} catch (e) { 589 console.error(`Failed to delete KVStore.code is ${e.code},message is ${e.message}`); 590} 591``` 592 593### deleteKVStore 594 595deleteKVStore(appId: string, storeId: string): Promise<void> 596 597Deletes a distributed KV store. This API uses a promise to return the result. 598 599**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 600 601**Parameters** 602 603| Name | Type| Mandatory| Description | 604| ------- | -------- | ---- | ------------------------------------------------------------ | 605| appId | string | Yes | Bundle name of the app that invokes the KV store. | 606| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 607 608**Return value** 609 610| Type | Description | 611| ------------------- | ------------------------- | 612| Promise<void> | Promise that returns no value.| 613 614**Error codes** 615 616For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 617 618| ID| **Error Message**| 619| ------------ | ------------ | 620| 15100004 | Not found. | 621 622**Example** 623 624```js 625let kvManager; 626let kvStore; 627const options = { 628 createIfMissing: true, 629 encrypt: false, 630 backup: false, 631 autoSync: true, 632 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 633 schema: undefined, 634 securityLevel: distributedKVStore.SecurityLevel.S2, 635} 636try { 637 kvManager.getKVStore('storeId', options).then(async (store) => { 638 console.info('Succeeded in getting KVStore'); 639 kvStore = store; 640 kvStore = null; 641 store = null; 642 kvManager.deleteKVStore('appId', 'storeId').then(() => { 643 console.info('Succeeded in deleting KVStore'); 644 }).catch((err) => { 645 console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`); 646 }); 647 }).catch((err) => { 648 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 649 }); 650} catch (e) { 651 console.error(`Failed to delete KVStore.code is ${e.code},message is ${e.message}`); 652} 653``` 654 655### getAllKVStoreId 656 657getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void 658 659Obtains the 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. 660 661**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 662 663**Parameters** 664 665| Name | Type | Mandatory| Description | 666| -------- | ----------------------------- | ---- | --------------------------------------------------- | 667| appId | string | Yes | Bundle name of the app that invokes the KV store. | 668| callback | AsyncCallback<string[]> | Yes | Callback invoked to return the IDs of all the distributed KV stores created.| 669 670**Example** 671 672```js 673let kvManager; 674try { 675 kvManager.getAllKVStoreId('appId', function (err, data) { 676 if (err != undefined) { 677 console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`); 678 return; 679 } 680 console.info('Succeeded in getting AllKVStoreId'); 681 console.info(`GetAllKVStoreId size = ${data.length}`); 682 }); 683} catch (e) { 684 console.error(`Failed to get AllKVStoreId.code is ${e.code},message is ${e.message}`); 685} 686``` 687 688### getAllKVStoreId 689 690getAllKVStoreId(appId: string): Promise<string[]> 691 692Obtains the 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. 693 694**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 695 696**Parameters** 697 698| Name| Type| Mandatory| Description | 699| ------ | -------- | ---- | ---------------------- | 700| appId | string | Yes | Bundle name of the app that invokes the KV store.| 701 702**Return value** 703 704| Type | Description | 705| ----------------------- | ------------------------------------------------------ | 706| Promise<string[]> | Promise used to return the IDs of all the distributed KV stores created. | 707 708**Example** 709 710```js 711let kvManager; 712try { 713 console.info('GetAllKVStoreId'); 714 kvManager.getAllKVStoreId('appId').then((data) => { 715 console.info('Succeeded in getting AllKVStoreId'); 716 console.info(`GetAllKVStoreId size = ${data.length}`); 717 }).catch((err) => { 718 console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`); 719 }); 720} catch (e) { 721 console.error(`Failed to get AllKVStoreId.code is ${e.code},message is ${e.message}`); 722} 723``` 724 725### on('distributedDataServiceDie') 726 727on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void 728 729Subscribes to service status changes. If the 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. 730 731**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 732 733**Parameters** 734 735| Name | Type | Mandatory| Description | 736| ------------- | -------------------- | ---- | ------------------------------------------------------------ | 737| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.| 738| deathCallback | Callback<void> | Yes | Callback invoked to return service status changes. | 739 740**Example** 741 742```js 743let kvManager; 744try { 745 console.info('KVManagerOn'); 746 const deathCallback = function () { 747 console.info('death callback call'); 748 } 749 kvManager.on('distributedDataServiceDie', deathCallback); 750} catch (e) { 751 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 752} 753``` 754 755### off('distributedDataServiceDie') 756 757off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void 758 759Unsubscribes from service status changes. The **deathCallback** parameter must be a callback registered for subscribing to service status changes. Otherwise, the unsubscription will fail. 760 761**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 762 763**Parameters** 764 765| Name | Type | Mandatory| Description | 766| ------------- | -------------------- | ---- | ------------------------------------------------------------ | 767| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates a service status change event.| 768| deathCallback | Callback<void> | No | Callback for the service status change event. If this parameter is not specified, all subscriptions to the service status change event will be canceled. | 769 770**Example** 771 772```js 773let kvManager; 774try { 775 console.info('KVManagerOff'); 776 const deathCallback = function () { 777 console.info('death callback call'); 778 } 779 kvManager.off('distributedDataServiceDie', deathCallback); 780} catch (e) { 781 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 782} 783``` 784 785## KVStoreResultSet 786 787Provides APIs for obtaining the distributed KV store result sets. A maximum of eight result sets can be opened at a time. 788 789Before calling any API in **KVStoreResultSet**, you must use **[getKVStore](#getkvstore)** to construct a **SingleKVStore** or **DeviceKVStore** instance. 790 791### getCount 792 793getCount(): number 794 795Obtains the total number of rows in the result set. 796 797**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 798 799**Return value** 800 801| Type | Description | 802| ------ | ------------------ | 803| number | Total number of rows obtained.| 804 805**Example** 806 807```js 808let kvStore; 809try { 810 let resultSet; 811 let count; 812 kvStore.getResultSet('batch_test_string_key').then((result) => { 813 console.info('getResultSet succeed.'); 814 resultSet = result; 815 count = resultSet.getCount(); 816 console.info("getCount succeed:" + count); 817 }).catch((err) => { 818 console.error('getResultSet failed: ' + err); 819 }); 820} catch (e) { 821 console.error("getCount failed: " + e); 822} 823``` 824 825### getPosition 826 827getPosition(): number 828 829Obtains 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). 830 831**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 832 833**Return value** 834 835| Type | Description | 836| ------ | ------------------ | 837| 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.| 838 839**Example** 840 841```js 842let kvStore; 843try { 844 let resultSet; 845 let position; 846 kvStore.getResultSet('batch_test_string_key').then((result) => { 847 console.info('getResultSet succeeded.'); 848 resultSet = result; 849 position = resultSet.getPosition(); 850 console.info("getPosition succeed:" + position); 851 }).catch((err) => { 852 console.error('getResultSet failed: ' + err); 853 }); 854} catch (e) { 855 console.error("getPosition failed: " + e); 856} 857``` 858 859### moveToFirst 860 861moveToFirst(): boolean 862 863Moves the data read position to the first row. If the result set is empty, **false** will be returned. 864 865**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 866 867**Return value** 868 869| Type | Description | 870| ------- | ----------------------------------------------- | 871| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 872 873**Example** 874 875```js 876let kvStore; 877try { 878 let resultSet; 879 let moved; 880 kvStore.getResultSet('batch_test_string_key').then((result) => { 881 console.info('getResultSet succeed.'); 882 resultSet = result; 883 moved = resultSet.moveToFirst(); 884 console.info("moveToFirst succeed: " + moved); 885 }).catch((err) => { 886 console.error('getResultSet failed: ' + err); 887 }); 888} catch (e) { 889 console.error("moveToFirst failed " + e); 890} 891``` 892 893### moveToLast 894 895moveToLast(): boolean 896 897Moves the data read position to the last row. If the result set is empty, **false** will be returned. 898 899**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 900 901**Return value** 902 903| Type | Description | 904| ------- | ----------------------------------------------- | 905| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 906 907**Example** 908 909```js 910let kvStore; 911try { 912 let resultSet; 913 let moved; 914 kvStore.getResultSet('batch_test_string_key').then((result) => { 915 console.info('getResultSet succeed.'); 916 resultSet = result; 917 moved = resultSet.moveToLast(); 918 console.info("moveToLast succeed:" + moved); 919 }).catch((err) => { 920 console.error('getResultSet failed: ' + err); 921 }); 922} catch (e) { 923 console.error("moveToLast failed: " + e); 924} 925``` 926 927### moveToNext 928 929moveToNext(): boolean 930 931Moves 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. 932 933**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 934 935**Return value** 936 937| Type | Description | 938| ------- | ----------------------------------------------- | 939| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 940 941**Example** 942 943```js 944let kvStore; 945try { 946 let resultSet; 947 let moved; 948 kvStore.getResultSet('batch_test_string_key').then((result) => { 949 console.info('getResultSet succeed.'); 950 resultSet = result; 951 do { 952 moved = resultSet.moveToNext(); 953 const entry = resultSet.getEntry(); 954 console.info("moveToNext succeed: " + moved); 955 } while (moved) 956 }).catch((err) => { 957 console.error('getResultSet failed: ' + err); 958 }); 959} catch (e) { 960 console.error("moveToNext failed: " + e); 961} 962``` 963 964### moveToPrevious 965 966moveToPrevious(): boolean 967 968Moves 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. 969 970**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 971 972**Return value** 973 974| Type | Description | 975| ------- | ----------------------------------------------- | 976| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 977 978**Example** 979 980```js 981let kvStore; 982try { 983 let resultSet; 984 let moved; 985 kvStore.getResultSet('batch_test_string_key').then((result) => { 986 console.info('getResultSet succeed.'); 987 resultSet = result; 988 moved = resultSet.moveToLast(); 989 moved = resultSet.moveToPrevious(); 990 console.info("moveToPrevious succeed:" + moved); 991 }).catch((err) => { 992 console.error('getResultSet failed: ' + err); 993 }); 994} catch (e) { 995 console.error("moveToPrevious failed: " + e); 996} 997``` 998 999### move 1000 1001move(offset: number): boolean 1002 1003Moves the data read position with the specified offset from the current position. That is, moves the number of rows specified by **offset** from the current position. 1004 1005**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1006 1007**Parameters** 1008 1009| Name| Type| Mandatory| Description | 1010| ------ | -------- | ---- | ------------------------------------------------------------ | 1011| 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.| 1012 1013**Return value** 1014 1015| Type | Description | 1016| ------- | ----------------------------------------------- | 1017| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 1018 1019**Example** 1020 1021```js 1022let kvStore; 1023try { 1024 let resultSet; 1025 let moved; 1026 kvStore.getResultSet('batch_test_string_key').then((result) => { 1027 console.info('Succeeded in getting resultSet'); 1028 resultSet = result; 1029 moved = resultSet.move(2); // If the current position is 0, move the read position forward by two rows, that is, move to row 3. 1030 console.info(`Succeeded in moving.moved = ${moved}`); 1031 }).catch((err) => { 1032 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 1033 }); 1034} catch (e) { 1035 console.error(`Failed to move.code is ${e.code},message is ${e.message}`); 1036} 1037``` 1038 1039### moveToPosition 1040 1041moveToPosition(position: number): boolean 1042 1043Moves the data read position from 0 to an absolute position. 1044 1045**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1046 1047**Parameters** 1048 1049| Name | Type| Mandatory| Description | 1050| -------- | -------- | ---- | -------------- | 1051| position | number | Yes | Absolute position to move to.| 1052 1053**Return value** 1054 1055| Type | Description | 1056| ------- | ----------------------------------------------- | 1057| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 1058 1059**Example** 1060 1061```js 1062let kvStore; 1063try { 1064 let resultSet; 1065 let moved; 1066 kvStore.getResultSet('batch_test_string_key').then((result) => { 1067 console.info('Succeeded in getting resultSet'); 1068 resultSet = result; 1069 moved = resultSet.moveToPosition(1); 1070 console.info(`Succeeded in moving to position.moved=${moved}`); 1071 }).catch((err) => { 1072 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 1073 }); 1074} catch (e) { 1075 console.error(`Failed to move to position.code is ${e.code},message is ${e.message}`); 1076} 1077``` 1078 1079### isFirst 1080 1081isFirst(): boolean 1082 1083Checks whether the data read position is the first row. 1084 1085**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1086 1087**Return value** 1088 1089| Type | Description | 1090| ------- | ------------------------------------------------------------ | 1091| boolean | Returns **true** if the first row is being read; returns **false** otherwise.| 1092 1093**Example** 1094 1095```js 1096let kvStore; 1097try { 1098 let resultSet; 1099 let isfirst; 1100 kvStore.getResultSet('batch_test_string_key').then((result) => { 1101 console.info('getResultSet succeed.'); 1102 resultSet = result; 1103 isfirst = resultSet.isFirst(); 1104 console.info("Check isFirst succeed:" + isfirst); 1105 }).catch((err) => { 1106 console.error('getResultSet failed: ' + err); 1107 }); 1108} catch (e) { 1109 console.error("Check isFirst failed: " + e); 1110} 1111``` 1112 1113### isLast 1114 1115isLast(): boolean 1116 1117Checks whether the data read position is the last row. 1118 1119**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1120 1121**Return value** 1122 1123| Type | Description | 1124| ------- | ------------------------------------------------------------ | 1125| boolean | Returns **true** if the last row is being read; returns **false** otherwise.| 1126 1127**Example** 1128 1129```js 1130let kvStore; 1131try { 1132 let resultSet; 1133 let islast; 1134 kvStore.getResultSet('batch_test_string_key').then((result) => { 1135 console.info('getResultSet succeed.'); 1136 resultSet = result; 1137 islast = resultSet.isLast(); 1138 console.info("Check isLast succeed: " + islast); 1139 }).catch((err) => { 1140 console.error('getResultSet failed: ' + err); 1141 }); 1142} catch (e) { 1143 console.error("Check isLast failed: " + e); 1144} 1145``` 1146 1147### isBeforeFirst 1148 1149isBeforeFirst(): boolean 1150 1151Checks whether the data read position is before the first row. 1152 1153**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1154 1155**Return value** 1156 1157| Type | Description | 1158| ------- | ------------------------------------------------------------ | 1159| boolean | Returns **true** if the data read position is before the first row; returns **false** otherwise.| 1160 1161**Example** 1162 1163```js 1164let kvStore; 1165try { 1166 let resultSet; 1167 kvStore.getResultSet('batch_test_string_key').then((result) => { 1168 console.info('getResultSet succeed.'); 1169 resultSet = result; 1170 const isbeforefirst = resultSet.isBeforeFirst(); 1171 console.info("Check isBeforeFirst succeed: " + isbeforefirst); 1172 }).catch((err) => { 1173 console.error('getResultSet failed: ' + err); 1174 }); 1175} catch (e) { 1176 console.error("Check isBeforeFirst failed: " + e); 1177} 1178``` 1179 1180### isAfterLast 1181 1182isAfterLast(): boolean 1183 1184Checks whether the data read position is after the last row. 1185 1186**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1187 1188**Return value** 1189 1190| Type | Description | 1191| ------- | ------------------------------------------------------------ | 1192| boolean | Returns **true** if the data read position is after the last row; returns **false** otherwise.| 1193 1194**Example** 1195 1196```js 1197let kvStore; 1198try { 1199 let resultSet; 1200 kvStore.getResultSet('batch_test_string_key').then((result) => { 1201 console.info('getResultSet succeed.'); 1202 resultSet = result; 1203 const isafterlast = resultSet.isAfterLast(); 1204 console.info("Check isAfterLast succeed:" + isafterlast); 1205 }).catch((err) => { 1206 console.error('getResultSet failed: ' + err); 1207 }); 1208} catch (e) { 1209 console.log("Check isAfterLast failed: " + e); 1210} 1211``` 1212 1213### getEntry 1214 1215getEntry(): Entry 1216 1217Obtains the KV pair from the current position. 1218 1219**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1220 1221**Return value** 1222 1223| Type | Description | 1224| --------------- | ------------ | 1225| [Entry](#entry) | KV pair obtained.| 1226 1227**Example** 1228 1229```js 1230let kvStore; 1231try { 1232 let resultSet; 1233 kvStore.getResultSet('batch_test_string_key').then((result) => { 1234 console.info('getResultSet succeed.'); 1235 resultSet = result; 1236 const entry = resultSet.getEntry(); 1237 console.info("getEntry succeed:" + JSON.stringify(entry)); 1238 }).catch((err) => { 1239 console.error('getResultSet failed: ' + err); 1240 }); 1241} catch (e) { 1242 console.error("getEntry failed: " + e); 1243} 1244``` 1245 1246## Query 1247 1248Provides methods to create a **Query** object, which defines different data query criteria. A **Query** object supports a maximum of 256 predicates. 1249 1250**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1251 1252### constructor 1253 1254constructor() 1255 1256A constructor used to create a **Schema** instance. 1257 1258**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1259 1260### reset 1261 1262reset(): Query 1263 1264Resets the **Query** object. 1265 1266**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1267 1268**Return value** 1269 1270| Type | Description | 1271| -------------- | --------------------- | 1272| [Query](#query) | **Query** object reset.| 1273 1274**Example** 1275 1276```js 1277try { 1278 let query = new distributedKVStore.Query(); 1279 query.equalTo("key", "value"); 1280 console.info("query is " + query.getSqlLike()); 1281 query.reset(); 1282 console.info("query is " + query.getSqlLike()); 1283 query = null; 1284} catch (e) { 1285 console.error("simply calls should be ok :" + e); 1286} 1287``` 1288 1289### equalTo 1290 1291equalTo(field: string, value: number|string|boolean): Query 1292 1293Creates a **Query** object to match the specified field whose value is equal to the given value. 1294 1295**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1296 1297**Parameters** 1298 1299| Name | Type| Mandatory | Description | 1300| ----- | ------ | ---- | ----------------------- | 1301| fieId | string | Yes |Field to match. It cannot contain '^'. | 1302| value | number\|string\|boolean | Yes | Value specified.| 1303 1304**Return value** 1305 1306| Type | Description | 1307| -------------- | --------------- | 1308| [Query](#query) | **Query** object created.| 1309 1310**Example** 1311 1312```js 1313try { 1314 let query = new distributedKVStore.Query(); 1315 query.equalTo("field", "value"); 1316 console.info(`query is ${query.getSqlLike()}`); 1317 query = null; 1318} catch (e) { 1319 console.error(`duplicated calls should be ok.ode is ${e.code},message is ${e.message}`); 1320} 1321``` 1322 1323### notEqualTo 1324 1325notEqualTo(field: string, value: number|string|boolean): Query 1326 1327Creates a **Query** object to match the specified field whose value is not equal to the specified value. 1328 1329**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1330 1331**Parameters** 1332 1333| Name | Type| Mandatory | Description | 1334| ----- | ------ | ---- | ----------------------- | 1335| fieId | string | Yes |Field to match. It cannot contain '^'. | 1336| value | number\|string\|boolean | Yes | Value specified.| 1337 1338**Return value** 1339 1340| Type | Description | 1341| -------------- | --------------- | 1342| [Query](#query) | **Query** object created.| 1343 1344**Example** 1345 1346```js 1347try { 1348 let query = new distributedKVStore.Query(); 1349 query.notEqualTo("field", "value"); 1350 console.info(`query is ${query.getSqlLike()}`); 1351 query = null; 1352} catch (e) { 1353 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1354} 1355``` 1356 1357### greaterThan 1358 1359greaterThan(field: string, value: number|string|boolean): Query 1360 1361Creates a **Query** object to match the specified field whose value is greater than the specified value. 1362 1363**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1364 1365**Parameters** 1366| Name | Type| Mandatory | Description | 1367| ----- | ------ | ---- | ----------------------- | 1368| fieId | string | Yes |Field to match. It cannot contain '^'. | 1369| value | number\|string\|boolean | Yes | Value specified.| 1370 1371**Return value** 1372 1373| Type | Description | 1374| -------------- | --------------- | 1375| [Query](#query) | **Query** object created.| 1376 1377**Example** 1378 1379```js 1380try { 1381 let query = new distributedKVStore.Query(); 1382 query.greaterThan("field", "value"); 1383 console.info(`query is ${query.getSqlLike()}`); 1384 query = null; 1385} catch (e) { 1386 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1387} 1388``` 1389 1390### lessThan 1391 1392lessThan(field: string, value: number|string): Query 1393 1394Creates a **Query** object to match the specified field whose value is less than the specified value. 1395 1396**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1397 1398**Parameters** 1399 1400 1401| Name | Type| Mandatory | Description | 1402| ----- | ------ | ---- | ----------------------- | 1403| fieId | string | Yes |Field to match. It cannot contain '^'. | 1404| value | number\|string | Yes | Value specified.| 1405 1406**Return value** 1407 1408| Type | Description | 1409| -------------- | --------------- | 1410| [Query](#query) | **Query** object created.| 1411 1412**Example** 1413 1414```js 1415try { 1416 let query = new distributedKVStore.Query(); 1417 query.lessThan("field", "value"); 1418 console.info(`query is ${query.getSqlLike()}`); 1419 query = null; 1420} catch (e) { 1421 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1422} 1423``` 1424 1425### greaterThanOrEqualTo 1426 1427greaterThanOrEqualTo(field: string, value: number|string): Query 1428 1429Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value. 1430 1431**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1432 1433**Parameters** 1434 1435 1436| Name | Type| Mandatory | Description | 1437| ----- | ------ | ---- | ----------------------- | 1438| fieId | string | Yes |Field to match. It cannot contain '^'. | 1439| value | number\|string | Yes | Value specified.| 1440 1441**Return value** 1442 1443| Type | Description | 1444| -------------- | --------------- | 1445| [Query](#query) | **Query** object created.| 1446 1447**Example** 1448 1449```js 1450try { 1451 let query = new distributedKVStore.Query(); 1452 query.greaterThanOrEqualTo("field", "value"); 1453 console.info(`query is ${query.getSqlLike()}`); 1454 query = null; 1455} catch (e) { 1456 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1457} 1458``` 1459 1460### lessThanOrEqualTo 1461 1462lessThanOrEqualTo(field: string, value: number|string): Query 1463 1464Creates a **Query** object to match the specified field whose value is less than or equal to the specified value. 1465 1466**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1467 1468**Parameters** 1469 1470 1471| Name | Type| Mandatory | Description | 1472| ----- | ------ | ---- | ----------------------- | 1473| fieId | string | Yes |Field to match. It cannot contain '^'. | 1474| value | number\|string | Yes | Value specified.| 1475 1476**Return value** 1477 1478| Type | Description | 1479| -------------- | --------------- | 1480| [Query](#query) | **Query** object created.| 1481 1482**Example** 1483 1484```js 1485try { 1486 let query = new distributedKVStore.Query(); 1487 query.lessThanOrEqualTo("field", "value"); 1488 console.info(`query is ${query.getSqlLike()}`); 1489 query = null; 1490} catch (e) { 1491 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1492} 1493``` 1494 1495### isNull 1496 1497isNull(field: string): Query 1498 1499Creates a **Query** object to match the specified field whose value is **null**. 1500 1501**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1502 1503**Parameters** 1504 1505| Name| Type| Mandatory| Description | 1506| ------ | -------- | ---- | ----------------------------- | 1507| fieId | string | Yes | Field to match. It cannot contain '^'.| 1508 1509**Return value** 1510 1511| Type | Description | 1512| -------------- | --------------- | 1513| [Query](#query) | **Query** object created.| 1514 1515**Example** 1516 1517```js 1518try { 1519 let query = new distributedKVStore.Query(); 1520 query.isNull("field"); 1521 console.info(`query is ${query.getSqlLike()}`); 1522 query = null; 1523} catch (e) { 1524 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1525} 1526``` 1527 1528### inNumber 1529 1530inNumber(field: string, valueList: number[]): Query 1531 1532Creates a **Query** object to match the specified field whose value is within the specified list of numbers. 1533 1534**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1535 1536**Parameters** 1537 1538| Name | Type| Mandatory| Description | 1539| --------- | -------- | ---- | ----------------------------- | 1540| fieId | string | Yes | Field to match. It cannot contain '^'.| 1541| valueList | number[] | Yes | List of numbers. | 1542 1543**Return value** 1544 1545| Type | Description | 1546| -------------- | --------------- | 1547| [Query](#query) | **Query** object created.| 1548 1549**Example** 1550 1551```js 1552try { 1553 let query = new distributedKVStore.Query(); 1554 query.inNumber("field", [0, 1]); 1555 console.info(`query is ${query.getSqlLike()}`); 1556 query = null; 1557} catch (e) { 1558 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1559} 1560``` 1561 1562### inString 1563 1564inString(field: string, valueList: string[]): Query 1565 1566Creates a **Query** object to match the specified field whose value is within the specified list of strings. 1567 1568**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1569 1570**Parameters** 1571 1572| Name | Type| Mandatory| Description | 1573| --------- | -------- | ---- | ----------------------------- | 1574| fieId | string | Yes | Field to match. It cannot contain '^'.| 1575| valueList | string[] | Yes | List of strings. | 1576 1577**Return value** 1578 1579| Type | Description | 1580| -------------- | --------------- | 1581| [Query](#query) | **Query** object created.| 1582 1583**Example** 1584 1585```js 1586try { 1587 let query = new distributedKVStore.Query(); 1588 query.inString("field", ['test1', 'test2']); 1589 console.info(`query is ${query.getSqlLike()}`); 1590 query = null; 1591} catch (e) { 1592 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1593} 1594``` 1595 1596### notInNumber 1597 1598notInNumber(field: string, valueList: number[]): Query 1599 1600Creates a **Query** object to match the specified field whose value is not within the specified list of numbers. 1601 1602**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1603 1604**Parameters** 1605 1606| Name | Type| Mandatory| Description | 1607| --------- | -------- | ---- | ----------------------------- | 1608| fieId | string | Yes | Field to match. It cannot contain '^'.| 1609| valueList | number[] | Yes | List of numbers. | 1610 1611**Return value** 1612 1613| Type | Description | 1614| -------------- | --------------- | 1615| [Query](#query) | **Query** object created.| 1616 1617**Example** 1618 1619```js 1620try { 1621 let query = new distributedKVStore.Query(); 1622 query.notInNumber("field", [0, 1]); 1623 console.info(`query is ${query.getSqlLike()}`); 1624 query = null; 1625} catch (e) { 1626 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1627} 1628``` 1629 1630### notInString 1631 1632notInString(field: string, valueList: string[]): Query 1633 1634Creates a **Query** object to match the specified field whose value is not within the specified list of strings. 1635 1636**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1637 1638**Parameters** 1639 1640| Name | Type| Mandatory| Description | 1641| --------- | -------- | ---- | ----------------------------- | 1642| fieId | string | Yes | Field to match. It cannot contain '^'.| 1643| valueList | string[] | Yes | List of strings. | 1644 1645**Return value** 1646 1647| Type | Description | 1648| -------------- | --------------- | 1649| [Query](#query) | **Query** object created.| 1650 1651**Example** 1652 1653```js 1654try { 1655 let query = new distributedKVStore.Query(); 1656 query.notInString("field", ['test1', 'test2']); 1657 console.info(`query is ${query.getSqlLike()}`); 1658 query = null; 1659} catch (e) { 1660 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1661} 1662``` 1663 1664### like 1665 1666like(field: string, value: string): Query 1667 1668Creates a **Query** object to match the specified field whose value is similar to the specified string. 1669 1670**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1671 1672**Parameters** 1673 1674| Name| Type| Mandatory| Description | 1675| ------ | -------- | ---- | ----------------------------- | 1676| fieId | string | Yes | Field to match. It cannot contain '^'.| 1677| value | string | Yes | String specified. | 1678 1679**Return value** 1680 1681| Type | Description | 1682| -------------- | --------------- | 1683| [Query](#query) | **Query** object created.| 1684 1685**Example** 1686 1687```js 1688try { 1689 let query = new distributedKVStore.Query(); 1690 query.like("field", "value"); 1691 console.info(`query is ${query.getSqlLike()}`); 1692 query = null; 1693} catch (e) { 1694 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1695} 1696``` 1697 1698### unlike 1699 1700unlike(field: string, value: string): Query 1701 1702Creates a **Query** object to match the specified field whose value is not similar to the specified string. 1703 1704**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1705 1706**Parameters** 1707 1708| Name| Type| Mandatory| Description | 1709| ------ | -------- | ---- | ----------------------------- | 1710| fieId | string | Yes | Field to match. It cannot contain '^'.| 1711| value | string | Yes | String specified. | 1712 1713**Return value** 1714 1715| Type | Description | 1716| -------------- | --------------- | 1717| [Query](#query) | **Query** object created.| 1718 1719**Example** 1720 1721```js 1722try { 1723 let query = new distributedKVStore.Query(); 1724 query.unlike("field", "value"); 1725 console.info(`query is ${query.getSqlLike()}`); 1726 query = null; 1727} catch (e) { 1728 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1729} 1730``` 1731 1732### and 1733 1734and(): Query 1735 1736Creates a **Query** object with the AND condition. 1737 1738**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1739 1740**Return value** 1741 1742| Type | Description | 1743| -------------- | -------------- | 1744| [Query](#query) | **Query** object created.| 1745 1746**Example** 1747 1748```js 1749try { 1750 let query = new distributedKVStore.Query(); 1751 query.notEqualTo("field", "value1"); 1752 query.and(); 1753 query.notEqualTo("field", "value2"); 1754 console.info("query is " + query.getSqlLike()); 1755 query = null; 1756} catch (e) { 1757 console.error("duplicated calls should be ok :" + e); 1758} 1759``` 1760 1761### or 1762 1763or(): Query 1764 1765Creates a **Query** object with the OR condition. 1766 1767**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1768 1769**Return value** 1770 1771| Type | Description | 1772| -------------- | -------------- | 1773| [Query](#query) | **Query** object created.| 1774 1775**Example** 1776 1777```js 1778try { 1779 let query = new distributedKVStore.Query(); 1780 query.notEqualTo("field", "value1"); 1781 query.or(); 1782 query.notEqualTo("field", "value2"); 1783 console.info("query is " + query.getSqlLike()); 1784 query = null; 1785} catch (e) { 1786 console.error("duplicated calls should be ok :" + e); 1787} 1788``` 1789 1790### orderByAsc 1791 1792orderByAsc(field: string): Query 1793 1794Creates a **Query** object to sort the query results in ascending order. 1795 1796**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1797 1798**Parameters** 1799 1800| Name| Type| Mandatory| Description | 1801| ------ | -------- | ---- | ----------------------------- | 1802| fieId | string | Yes | Field to match. It cannot contain '^'.| 1803 1804**Return value** 1805 1806| Type | Description | 1807| -------------- | --------------- | 1808| [Query](#query) | **Query** object created.| 1809 1810**Example** 1811 1812```js 1813try { 1814 let query = new distributedKVStore.Query(); 1815 query.notEqualTo("field", "value"); 1816 query.orderByAsc("field"); 1817 console.info(`query is ${query.getSqlLike()}`); 1818 query = null; 1819} catch (e) { 1820 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1821} 1822``` 1823 1824### orderByDesc 1825 1826orderByDesc(field: string): Query 1827 1828Creates a **Query** object to sort the query results in descending order. 1829 1830**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1831 1832**Parameters** 1833 1834| Name| Type| Mandatory| Description | 1835| ------ | -------- | ---- | ----------------------------- | 1836| fieId | string | Yes | Field to match. It cannot contain '^'.| 1837 1838**Return value** 1839 1840| Type | Description | 1841| -------------- | --------------- | 1842| [Query](#query) | **Query** object created.| 1843 1844**Example** 1845 1846```js 1847try { 1848 let query = new distributedKVStore.Query(); 1849 query.notEqualTo("field", "value"); 1850 query.orderByDesc("field"); 1851 console.info(`query is ${query.getSqlLike()}`); 1852 query = null; 1853} catch (e) { 1854 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1855} 1856``` 1857 1858### limit 1859 1860limit(total: number, offset: number): Query 1861 1862Creates 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. 1863 1864**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1865 1866**Parameters** 1867 1868| Name| Type| Mandatory| Description | 1869| ------ | -------- | ---- | ------------------ | 1870| total | number | Yes | Number of results to query.| 1871| offset | number | Yes | Start position for query. | 1872 1873**Return value** 1874 1875| Type | Description | 1876| -------------- | --------------- | 1877| [Query](#query) | **Query** object created.| 1878 1879**Example** 1880 1881```js 1882let total = 10; 1883let offset = 1; 1884try { 1885 let query = new distributedKVStore.Query(); 1886 query.notEqualTo("field", "value"); 1887 query.limit(total, offset); 1888 console.info(`query is ${query.getSqlLike()}`); 1889 query = null; 1890} catch (e) { 1891 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1892} 1893``` 1894 1895### isNotNull 1896 1897isNotNull(field: string): Query 1898 1899Creates a **Query** object to match the specified field whose value is not **null**. 1900 1901**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1902 1903**Parameters** 1904 1905| Name| Type| Mandatory| Description | 1906| ------ | -------- | ---- | ----------------------------- | 1907| fieId | string | Yes | Field to match. It cannot contain '^'.| 1908 1909**Return value** 1910 1911| Type | Description | 1912| -------------- | --------------- | 1913| [Query](#query) | **Query** object created.| 1914 1915**Example** 1916 1917```js 1918try { 1919 let query = new distributedKVStore.Query(); 1920 query.isNotNull("field"); 1921 console.info(`query is ${query.getSqlLike()}`); 1922 query = null; 1923} catch (e) { 1924 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 1925} 1926``` 1927 1928### beginGroup 1929 1930beginGroup(): Query 1931 1932Creates a **Query** object for a query condition group with a left parenthesis. 1933 1934**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1935 1936**Return value** 1937 1938| Type | Description | 1939| -------------- | --------------- | 1940| [Query](#query) | **Query** object created.| 1941 1942**Example** 1943 1944```js 1945try { 1946 let query = new distributedKVStore.Query(); 1947 query.beginGroup(); 1948 query.isNotNull("field"); 1949 query.endGroup(); 1950 console.info("query is " + query.getSqlLike()); 1951 query = null; 1952} catch (e) { 1953 console.error("duplicated calls should be ok :" + e); 1954} 1955``` 1956 1957### endGroup 1958 1959endGroup(): Query 1960 1961Creates a **Query** object for a query condition group with a right parenthesis. 1962 1963**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1964 1965**Return value** 1966 1967| Type | Description | 1968| -------------- | --------------- | 1969| [Query](#query) | **Query** object created.| 1970 1971**Example** 1972 1973```js 1974try { 1975 let query = new distributedKVStore.Query(); 1976 query.beginGroup(); 1977 query.isNotNull("field"); 1978 query.endGroup(); 1979 console.info("query is " + query.getSqlLike()); 1980 query = null; 1981} catch (e) { 1982 console.error("duplicated calls should be ok :" + e); 1983} 1984``` 1985 1986### prefixKey 1987 1988prefixKey(prefix: string): Query 1989 1990Creates a **Query** object with a specified key prefix. 1991 1992**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1993 1994**Parameters** 1995 1996| Name| Type| Mandatory| Description | 1997| ------ | -------- | ---- | ------------------ | 1998| prefix | string | Yes | Key prefix.| 1999 2000**Return value** 2001 2002| Type | Description | 2003| -------------- | --------------- | 2004| [Query](#query) | **Query** object created.| 2005 2006**Example** 2007 2008```js 2009try { 2010 let query = new distributedKVStore.Query(); 2011 query.prefixKey("$.name"); 2012 query.prefixKey("0"); 2013 console.info(`query is ${query.getSqlLike()}`); 2014 query = null; 2015} catch (e) { 2016 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 2017} 2018``` 2019 2020### setSuggestIndex 2021 2022setSuggestIndex(index: string): Query 2023 2024Creates a **Query** object with an index preferentially used for query. 2025 2026**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2027 2028**Parameters** 2029 2030| Name| Type| Mandatory| Description | 2031| ------ | -------- | ---- | ------------------ | 2032| index | string | Yes | Index preferentially used for query.| 2033 2034**Return value** 2035 2036| Type | Description | 2037| -------------- | --------------- | 2038| [Query](#query) | **Query** object created.| 2039 2040**Example** 2041 2042```js 2043try { 2044 let query = new distributedKVStore.Query(); 2045 query.setSuggestIndex("$.name"); 2046 query.setSuggestIndex("0"); 2047 console.info(`query is ${query.getSqlLike()}`); 2048 query = null; 2049} catch (e) { 2050 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 2051} 2052``` 2053 2054### deviceId 2055 2056deviceId(deviceId:string):Query 2057 2058Creates a **Query** object with the device ID as the key prefix. 2059 2060**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2061 2062**Parameters** 2063 2064| Name | Type| Mandatory| Description | 2065| -------- | -------- | ---- | ------------------ | 2066| deviceId | string | Yes | Device ID.| 2067 2068**Return value** 2069 2070| Type | Description | 2071| -------------- | --------------- | 2072| [Query](#query) | **Query** object created.| 2073 2074**Example** 2075 2076```js 2077try { 2078 let query = new distributedKVStore.Query(); 2079 query.deviceId("deviceId"); 2080 console.info(`query is ${query.getSqlLike()}`); 2081} catch (e) { 2082 console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); 2083} 2084``` 2085 2086### getSqlLike 2087 2088getSqlLike():string 2089 2090Obtains the query statement of the **Query** object. 2091 2092**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2093 2094**Return value** 2095 2096| Type | Description | 2097| ------ | ------------------------------------ | 2098| string | Returns the query statement obtained.| 2099 2100**Example** 2101 2102```js 2103try { 2104 let query = new distributedKVStore.Query(); 2105 let sql1 = query.getSqlLike(); 2106 console.info(`GetSqlLike sql= ${sql1}`); 2107} catch (e) { 2108 console.error("duplicated calls should be ok : " + e); 2109} 2110``` 2111 2112## SingleKVStore 2113 2114Implements data management in a single KV store, such as adding data, deleting data, and subscribing to data changes or data synchronization completion. 2115 2116Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance. 2117 2118### put 2119 2120put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void 2121 2122Adds a KV pair of the specified type to this KV store. This API uses an asynchronous callback to return the result. 2123 2124**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2125 2126**Parameters** 2127 2128| Name | Type| Mandatory | Description | 2129| ----- | ------ | ---- | ----------------------- | 2130| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | 2131| 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). | 2132| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | 2133 2134**Error codes** 2135 2136For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2137 2138| ID| **Error Message** | 2139| ------------ | -------------------------------------- | 2140| 15100003 | Database corrupted. | 2141| 15100005 | Database or result set already closed. | 2142 2143**Example** 2144 2145```js 2146let kvStore; 2147const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2148const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2149try { 2150 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err) { 2151 if (err != undefined) { 2152 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 2153 return; 2154 } 2155 console.info("Succeeded in putting"); 2156 }); 2157} catch (e) { 2158 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 2159} 2160``` 2161 2162### put 2163 2164put(key: string, value: Uint8Array | string | number | boolean): Promise<void> 2165 2166Adds a KV pair of the specified type to this KV store. This API uses a promise to return the result. 2167 2168**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2169 2170**Parameters** 2171 2172| Name | Type| Mandatory | Description | 2173| ----- | ------ | ---- | ----------------------- | 2174| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | 2175| 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). | 2176 2177**Return value** 2178 2179| Type | Description | 2180| ------------------- | ------------------------- | 2181| Promise<void> | Promise that returns no value.| 2182 2183**Error codes** 2184 2185For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2186 2187| ID| **Error Message** | 2188| ------------ | -------------------------------------- | 2189| 15100003 | Database corrupted. | 2190| 15100005 | Database or result set already closed. | 2191 2192**Example** 2193 2194```js 2195let kvStore; 2196const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2197const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2198try { 2199 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { 2200 console.info(`Succeeded in putting data`); 2201 }).catch((err) => { 2202 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 2203 }); 2204} catch (e) { 2205 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 2206} 2207``` 2208 2209### putBatch 2210 2211putBatch(entries: Entry[], callback: AsyncCallback<void>): void 2212 2213Batch inserts KV pairs to this single KV store. This API uses an asynchronous callback to return the result. 2214 2215**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2216 2217**Parameters** 2218 2219| Name | Type | Mandatory| Description | 2220| -------- | ------------------------ | ---- | ------------------------ | 2221| entries | [Entry](#entry)[] | Yes | KV pairs to insert in batches. An **entries** object allows a maximum of 128 entries.| 2222| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 2223 2224**Error codes** 2225 2226For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2227 2228| ID| **Error Message** | 2229| ------------ | -------------------------------------- | 2230| 15100003 | Database corrupted. | 2231| 15100005 | Database or result set already closed. | 2232 2233**Example** 2234 2235```js 2236let kvStore; 2237try { 2238 let entries = []; 2239 for (var i = 0; i < 10; i++) { 2240 var key = 'batch_test_string_key'; 2241 var entry = { 2242 key: key + i, 2243 value: { 2244 type: distributedKVStore.ValueType.STRING, 2245 value: 'batch_test_string_value' 2246 } 2247 } 2248 entries.push(entry); 2249 } 2250 console.info(`entries: ${entries}`); 2251 kvStore.putBatch(entries, async function (err) { 2252 if (err != undefined) { 2253 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 2254 return; 2255 } 2256 console.info('Succeeded in putting Batch'); 2257 kvStore.getEntries('batch_test_string_key', function (err, entries) { 2258 if (err != undefined) { 2259 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 2260 } 2261 console.info('Succeeded in getting Entries'); 2262 console.info(`entries.length: ${entries.length}`); 2263 console.info(`entries[0]: ${entries[0]}`); 2264 }); 2265 }); 2266} catch (e) { 2267 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); 2268} 2269``` 2270 2271### putBatch 2272 2273putBatch(entries: Entry[]): Promise<void> 2274 2275Batch inserts KV pairs to this single KV store. This API uses a promise to return the result. 2276 2277**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2278 2279**Parameters** 2280 2281| Name | Type | Mandatory| Description | 2282| ------- | ----------------- | ---- | ------------------------ | 2283| entries | [Entry](#entry)[] | Yes | KV pairs to insert in batches. An **entries** object allows a maximum of 128 entries.| 2284 2285**Return value** 2286 2287| Type | Description | 2288| ------------------- | ------------------------- | 2289| Promise<void> | Promise that returns no value.| 2290 2291**Error codes** 2292 2293For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2294 2295| ID| **Error Message** | 2296| ------------ | -------------------------------------- | 2297| 15100003 | Database corrupted. | 2298| 15100005 | Database or result set already closed. | 2299 2300**Example** 2301 2302```js 2303let kvStore; 2304try { 2305 let entries = []; 2306 for (var i = 0; i < 10; i++) { 2307 var key = 'batch_test_string_key'; 2308 var entry = { 2309 key: key + i, 2310 value: { 2311 type: distributedKVStore.ValueType.STRING, 2312 value: 'batch_test_string_value' 2313 } 2314 } 2315 entries.push(entry); 2316 } 2317 console.info(`entries: ${entries}`); 2318 kvStore.putBatch(entries).then(async () => { 2319 console.info('Succeeded in putting Batch'); 2320 kvStore.getEntries('batch_test_string_key').then((entries) => { 2321 console.info('Succeeded in getting Entries'); 2322 console.info(`PutBatch ${entries}`); 2323 }).catch((err) => { 2324 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 2325 }); 2326 }).catch((err) => { 2327 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 2328 }); 2329} catch (e) { 2330 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); 2331} 2332``` 2333 2334### putBatch 2335 2336putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void 2337 2338Writes data to this single KV store. This API uses an asynchronous callback to return the result. 2339 2340**System API**: This is a system API. 2341 2342**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2343 2344**Parameters** 2345 2346| Name | Type | Mandatory| Description | 2347| -------- | ------------------------------------------------------------ | ---- | ------------------ | 2348| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write.| 2349| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 2350 2351**Error codes** 2352 2353For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2354 2355| ID| **Error Message** | 2356| ------------ | -------------------------------------- | 2357| 15100003 | Database corrupted. | 2358| 15100005 | Database or result set already closed. | 2359 2360**Example** 2361 2362```js 2363let kvStore; 2364try { 2365 let v8Arr = []; 2366 let arr = new Uint8Array([4, 5, 6, 7]); 2367 let vb1 = { key: "name_1", value: 32 } 2368 let vb2 = { key: "name_2", value: arr }; 2369 let vb3 = { key: "name_3", value: "lisi" }; 2370 2371 v8Arr.push(vb1); 2372 v8Arr.push(vb2); 2373 v8Arr.push(vb3); 2374 kvStore.putBatch(v8Arr, async function (err) { 2375 if (err != undefined) { 2376 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 2377 return; 2378 } 2379 console.info('Succeeded in putting batch'); 2380 }) 2381} catch (e) { 2382 console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`); 2383} 2384``` 2385 2386### putBatch 2387 2388putBatch(value: Array<ValuesBucket>): Promise<void> 2389 2390Write data to this KV store. This API uses a promise to return the result. 2391 2392**System API**: This is a system API. 2393 2394**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2395 2396**Parameters** 2397 2398| Name| Type | Mandatory| Description | 2399| ------ | ------------------------------------------------------------ | ---- | ------------------ | 2400| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write. | 2401 2402**Return value** 2403 2404| Type | Description | 2405| ------------------- | ------------------------- | 2406| Promise<void> | Promise that returns no value.| 2407 2408**Error codes** 2409 2410For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2411 2412| ID| **Error Message** | 2413| ------------ | -------------------------------------- | 2414| 15100003 | Database corrupted. | 2415| 15100005 | Database or result set already closed. | 2416 2417**Example** 2418 2419```js 2420let kvStore; 2421try { 2422 let v8Arr = []; 2423 let arr = new Uint8Array([4, 5, 6, 7]); 2424 let vb1 = { key: "name_1", value: 32 } 2425 let vb2 = { key: "name_2", value: arr }; 2426 let vb3 = { key: "name_3", value: "lisi" }; 2427 2428 v8Arr.push(vb1); 2429 v8Arr.push(vb2); 2430 v8Arr.push(vb3); 2431 kvStore.putBatch(v8Arr).then(async () => { 2432 console.info(`Succeeded in putting patch`); 2433 }).catch((err) => { 2434 console.error(`putBatch fail.code is ${err.code},message is ${err.message}`); 2435 }); 2436} catch (e) { 2437 console.error(`putBatch fail.code is ${e.code},message is ${e.message}`); 2438} 2439``` 2440 2441### delete 2442 2443delete(key: string, callback: AsyncCallback<void>): void 2444 2445Deletes a KV pair from this KV store. This API uses an asynchronous callback to return the result. 2446 2447**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2448 2449**Parameters** 2450 2451| Name | Type | Mandatory| Description | 2452| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 2453| key | string | Yes | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 2454| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 2455 2456**Error codes** 2457 2458For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2459 2460| ID| **Error Message** | 2461| ------------ | -------------------------------------- | 2462| 15100003 | Database corrupted. | 2463| 15100005 | Database or result set already closed. | 2464 2465**Example** 2466 2467```js 2468let kvStore; 2469const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2470const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2471try { 2472 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err) { 2473 if (err != undefined) { 2474 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 2475 return; 2476 } 2477 console.info('Succeeded in putting'); 2478 kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err) { 2479 if (err != undefined) { 2480 console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); 2481 return; 2482 } 2483 console.info('Succeeded in deleting'); 2484 }); 2485 }); 2486} catch (e) { 2487 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 2488} 2489``` 2490 2491### delete 2492 2493delete(key: string): Promise<void> 2494 2495Deletes a KV pair from this KV store. This API uses a promise to return the result. 2496 2497**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2498 2499**Parameters** 2500 2501| Name| Type| Mandatory| Description | 2502| ------ | -------- | ---- | ------------------------------------------------------------ | 2503| key | string | Yes | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 2504 2505**Return value** 2506 2507| Type | Description | 2508| ------------------- | ------------------------- | 2509| Promise<void> | Promise that returns no value.| 2510 2511**Error codes** 2512 2513For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2514 2515| ID| **Error Message** | 2516| ------------ | -------------------------------------- | 2517| 15100003 | Database corrupted. | 2518| 15100005 | Database or result set already closed. | 2519 2520**Example** 2521 2522```js 2523let kvStore; 2524const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2525const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2526try { 2527 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { 2528 console.info(`Succeeded in putting data`); 2529 kvStore.delete(KEY_TEST_STRING_ELEMENT).then(() => { 2530 console.info('Succeeded in deleting'); 2531 }).catch((err) => { 2532 console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); 2533 }); 2534 }).catch((err) => { 2535 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 2536 }); 2537} catch (e) { 2538 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 2539} 2540``` 2541 2542### delete 2543 2544delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) 2545 2546Deletes KV pairs from this KV store. This API uses an asynchronous callback to return the result. 2547 2548**System API**: This is a system API. 2549 2550**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 2551 2552**Parameters** 2553 2554| Name | Type | Mandatory| Description | 2555| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | 2556| 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.| 2557| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 2558 2559**Error codes** 2560 2561For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2562 2563| ID| **Error Message** | 2564| ------------ | -------------------------------------- | 2565| 15100003 | Database corrupted. | 2566| 15100005 | Database or result set already closed. | 2567 2568**Example** 2569 2570```js 2571import dataSharePredicates from '@ohos.data.dataSharePredicates'; 2572let kvStore; 2573try { 2574 let predicates = new dataSharePredicates.DataSharePredicates(); 2575 kvStore.delete(predicates, function (err) { 2576 if (err == undefined) { 2577 console.info('Succeeded in deleting'); 2578 } else { 2579 console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); 2580 } 2581 }); 2582} catch (e) { 2583 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 2584} 2585``` 2586 2587### delete 2588 2589delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> 2590 2591Deletes KV pairs from this KV store. This API uses a promise to return the result. 2592 2593**System API**: This is a system API. 2594 2595**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 2596 2597**Parameters** 2598 2599| Name | Type | Mandatory| Description | 2600| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | 2601| 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.| 2602 2603**Return value** 2604 2605| Type | Description | 2606| ------------------- | ------------------------- | 2607| Promise<void> | Promise that returns no value.| 2608 2609**Error codes** 2610 2611For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2612 2613| ID| **Error Message** | 2614| ------------ | -------------------------------------- | 2615| 15100003 | Database corrupted. | 2616| 15100005 | Database or result set already closed. | 2617 2618**Example** 2619 2620```js 2621import dataSharePredicates from '@ohos.data.dataSharePredicates'; 2622 2623let kvStore; 2624try { 2625 let predicates = new dataSharePredicates.DataSharePredicates(); 2626 let arr = ["name"]; 2627 predicates.inKeys(arr); 2628 kvStore.put("name", "bob").then(() => { 2629 console.info(`Succeeded in putting data`); 2630 kvStore.delete(predicates).then(() => { 2631 console.info('Succeeded in deleting'); 2632 }).catch((err) => { 2633 console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); 2634 }); 2635 }).catch((err) => { 2636 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 2637 }); 2638} catch (e) { 2639 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 2640} 2641``` 2642 2643### deleteBatch 2644 2645deleteBatch(keys: string[], callback: AsyncCallback<void>): void 2646 2647Batch deletes KV pairs from this single KV store. This API uses an asynchronous callback to return the result. 2648 2649**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2650 2651**Parameters** 2652 2653| Name | Type | Mandatory| Description | 2654| -------- | ------------------------- | ---- | ------------------------ | 2655| keys | string[] | Yes | KV pairs to delete in batches.| 2656| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 2657 2658**Error codes** 2659 2660For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2661 2662| ID| **Error Message** | 2663| ------------ | -------------------------------------- | 2664| 15100003 | Database corrupted. | 2665| 15100005 | Database or result set already closed. | 2666 2667**Example** 2668 2669```js 2670let kvStore; 2671try { 2672 let entries = []; 2673 let keys = []; 2674 for (var i = 0; i < 5; i++) { 2675 var key = 'batch_test_string_key'; 2676 var entry = { 2677 key: key + i, 2678 value: { 2679 type: distributedKVStore.ValueType.STRING, 2680 value: 'batch_test_string_value' 2681 } 2682 } 2683 entries.push(entry); 2684 keys.push(key + i); 2685 } 2686 console.info(`entries: ${entries}`); 2687 kvStore.putBatch(entries, async function (err) { 2688 if (err != undefined) { 2689 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 2690 return; 2691 } 2692 console.info('Succeeded in putting Batch'); 2693 kvStore.deleteBatch(keys, async function (err) { 2694 if (err != undefined) { 2695 console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`); 2696 return; 2697 } 2698 console.info('Succeeded in deleting Batch'); 2699 }); 2700 }); 2701} catch (e) { 2702 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 2703} 2704``` 2705 2706### deleteBatch 2707 2708deleteBatch(keys: string[]): Promise<void> 2709 2710Batch deletes KV pairs from this single KV store. This API uses a promise to return the result. 2711 2712**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2713 2714**Parameters** 2715 2716| Name| Type| Mandatory| Description | 2717| ------ | -------- | ---- | ------------------------ | 2718| keys | string[] | Yes | KV pairs to delete in batches.| 2719 2720**Return value** 2721 2722| Type | Description | 2723| ------------------- | ------------------------- | 2724| Promise<void> | Promise that returns no value.| 2725 2726**Error codes** 2727 2728For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2729 2730| ID| **Error Message** | 2731| ------------ | -------------------------------------- | 2732| 15100003 | Database corrupted. | 2733| 15100005 | Database or result set already closed. | 2734 2735**Example** 2736 2737```js 2738let kvStore; 2739try { 2740 let entries = []; 2741 let keys = []; 2742 for (var i = 0; i < 5; i++) { 2743 var key = 'batch_test_string_key'; 2744 var entry = { 2745 key: key + i, 2746 value: { 2747 type: distributedKVStore.ValueType.STRING, 2748 value: 'batch_test_string_value' 2749 } 2750 } 2751 entries.push(entry); 2752 keys.push(key + i); 2753 } 2754 console.info(`entries: ${entries}`); 2755 kvStore.putBatch(entries).then(async () => { 2756 console.info('Succeeded in putting Batch'); 2757 kvStore.deleteBatch(keys).then(() => { 2758 console.info('Succeeded in deleting Batch'); 2759 }).catch((err) => { 2760 console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`); 2761 }); 2762 }).catch((err) => { 2763 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 2764 }); 2765} catch (e) { 2766 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 2767} 2768``` 2769 2770### removeDeviceData 2771 2772removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void 2773 2774Deletes data of a device. This API uses an asynchronous callback to return the result. 2775 2776**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 2777 2778**Parameters** 2779 2780| Name | Type | Mandatory| Description | 2781| -------- | ------------------------- | ---- | ---------------------- | 2782| deviceId | string | Yes | ID of the target device.| 2783| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 2784 2785**Error codes** 2786 2787For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2788 2789| ID| **Error Message** | 2790| ------------ | -------------------------------------- | 2791| 15100005 | Database or result set already closed. | 2792 2793**Example** 2794 2795```js 2796let kvStore; 2797const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 2798const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; 2799try { 2800 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err) { 2801 console.info('Succeeded in putting data'); 2802 const deviceid = 'no_exist_device_id'; 2803 kvStore.removeDeviceData(deviceid, async function (err) { 2804 if (err == undefined) { 2805 console.info('succeeded in removing device data'); 2806 } else { 2807 console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `); 2808 kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err, data) { 2809 console.info('Succeeded in getting data'); 2810 }); 2811 } 2812 }); 2813 }); 2814} catch (e) { 2815 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`) 2816} 2817``` 2818 2819### removeDeviceData 2820 2821removeDeviceData(deviceId: string): Promise<void> 2822 2823Deletes data of a device. This API uses a promise to return the result. 2824 2825**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 2826 2827**Parameters** 2828 2829| Name | Type| Mandatory| Description | 2830| -------- | -------- | ---- | ---------------------- | 2831| deviceId | string | Yes | ID of the target device.| 2832 2833**Return value** 2834 2835| Type | Description | 2836| ------------------- | ------------------------- | 2837| Promise<void> | Promise that returns no value.| 2838 2839**Error codes** 2840 2841For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2842 2843| ID| **Error Message** | 2844| ------------ | -------------------------------------- | 2845| 15100005 | Database or result set already closed. | 2846 2847**Example** 2848 2849```js 2850let kvStore; 2851const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 2852const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; 2853try { 2854 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { 2855 console.info('Succeeded in putting data'); 2856 }).catch((err) => { 2857 console.error(`Failed to put data.code is ${err.code},message is ${err.message} `); 2858 }); 2859 const deviceid = 'no_exist_device_id'; 2860 kvStore.removeDeviceData(deviceid).then(() => { 2861 console.info('succeeded in removing device data'); 2862 }).catch((err) => { 2863 console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `); 2864 }); 2865 kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { 2866 console.info('Succeeded in getting data'); 2867 }).catch((err) => { 2868 console.error(`Failed to get data.code is ${err.code},message is ${err.message} `); 2869 }); 2870} catch (e) { 2871 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`) 2872} 2873``` 2874 2875### get 2876 2877get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 2878 2879Obtains the value of the specified key. This API uses an asynchronous callback to return the result. 2880 2881**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2882 2883**Parameters** 2884 2885| Name | Type| Mandatory | Description | 2886| ----- | ------ | ---- | ----------------------- | 2887| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | 2888| callback |AsyncCallback<boolean \| string \| number \| Uint8Array> | Yes |Callback invoked to return the value obtained. | 2889 2890**Error codes** 2891 2892For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2893 2894| ID| **Error Message** | 2895| ------------ | -------------------------------------- | 2896| 15100003 | Database corrupted. | 2897| 15100004 | Not found. | 2898| 15100005 | Database or result set already closed. | 2899 2900**Example** 2901 2902```js 2903let kvStore; 2904const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2905const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2906try { 2907 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err) { 2908 if (err != undefined) { 2909 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 2910 return; 2911 } 2912 console.info("Succeeded in putting"); 2913 kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { 2914 if (err != undefined) { 2915 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 2916 return; 2917 } 2918 console.info(`Succeeded in getting data.data=${data}`); 2919 }); 2920 }); 2921} catch (e) { 2922 console.error(`Failed to get.code is ${e.code},message is ${e.message}`); 2923} 2924``` 2925 2926### get 2927 2928get(key: string): Promise<boolean | string | number | Uint8Array> 2929 2930Obtains the value of the specified key. This API uses a promise to return the result. 2931 2932**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2933 2934**Parameters** 2935 2936| Name| Type| Mandatory| Description | 2937| ------ | -------- | ---- | ------------------------------------------------------------ | 2938| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 2939 2940**Return value** 2941 2942| Type | Description | 2943| ------ | ------- | 2944|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.| 2945 2946**Error codes** 2947 2948For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2949 2950| ID| **Error Message** | 2951| ------------ | -------------------------------------- | 2952| 15100003 | Database corrupted. | 2953| 15100004 | Not found. | 2954| 15100005 | Database or result set already closed. | 2955 2956**Example** 2957 2958```js 2959let kvStore; 2960const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2961const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2962try { 2963 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { 2964 console.info(`Succeeded in putting data`); 2965 kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { 2966 console.info(`Succeeded in getting data.data=${data}`); 2967 }).catch((err) => { 2968 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 2969 }); 2970 }).catch((err) => { 2971 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 2972 }); 2973} catch (e) { 2974 console.error(`Failed to get.code is ${e.code},message is ${e.message}`); 2975} 2976``` 2977 2978### getEntries 2979 2980getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void 2981 2982Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. 2983 2984**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2985 2986**Parameters** 2987 2988| Name | Type | Mandatory| Description | 2989| --------- | -------------------------------------- | ---- | ---------------------------------------- | 2990| keyPrefix | string | Yes | Key prefix to match. | 2991| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs that match the specified prefix.| 2992 2993**Error codes** 2994 2995For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2996 2997| ID| **Error Message** | 2998| ------------ | -------------------------------------- | 2999| 15100003 | Database corrupted. | 3000| 15100005 | Database or result set already closed. | 3001 3002**Example** 3003 3004```js 3005let kvStore; 3006try { 3007 let entries = []; 3008 for (var i = 0; i < 10; i++) { 3009 var key = 'batch_test_string_key'; 3010 var entry = { 3011 key: key + i, 3012 value: { 3013 type: distributedKVStore.ValueType.STRING, 3014 value: 'batch_test_string_value' 3015 } 3016 } 3017 entries.push(entry); 3018 } 3019 console.info(`entries: ${entries}`); 3020 kvStore.putBatch(entries, async function (err) { 3021 if (err != undefined) { 3022 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 3023 return; 3024 } 3025 console.info('Succeeded in putting Batch'); 3026 kvStore.getEntries('batch_test_string_key', function (err, entries) { 3027 if (err != undefined) { 3028 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 3029 return; 3030 } 3031 console.info('Succeeded in getting Entries'); 3032 console.info(`entries.length: ${entries.length}`); 3033 console.info(`entries[0]: ${entries[0]}`); 3034 }); 3035 }); 3036} catch (e) { 3037 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); 3038} 3039``` 3040 3041### getEntries 3042 3043getEntries(keyPrefix: string): Promise<Entry[]> 3044 3045Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result. 3046 3047**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3048 3049**Parameters** 3050 3051| Name | Type| Mandatory| Description | 3052| --------- | -------- | ---- | -------------------- | 3053| keyPrefix | string | Yes | Key prefix to match.| 3054 3055**Return value** 3056 3057| Type | Description | 3058| -------------------------------- | ------------------------------------------- | 3059| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified prefix.| 3060 3061**Error codes** 3062 3063For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3064 3065| ID| **Error Message** | 3066| ------------ | -------------------------------------- | 3067| 15100003 | Database corrupted. | 3068| 15100005 | Database or result set already closed. | 3069 3070**Example** 3071 3072```js 3073let kvStore; 3074try { 3075 let entries = []; 3076 for (var i = 0; i < 10; i++) { 3077 var key = 'batch_test_string_key'; 3078 var entry = { 3079 key: key + i, 3080 value: { 3081 type: distributedKVStore.ValueType.STRING, 3082 value: 'batch_test_string_value' 3083 } 3084 } 3085 entries.push(entry); 3086 } 3087 console.info(`entries: ${entries}`); 3088 kvStore.putBatch(entries).then(async () => { 3089 console.info('Succeeded in putting Batch'); 3090 kvStore.getEntries('batch_test_string_key').then((entries) => { 3091 console.info('Succeeded in getting Entries'); 3092 console.info(`PutBatch ${entries}`); 3093 }).catch((err) => { 3094 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 3095 }); 3096 }).catch((err) => { 3097 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 3098 }); 3099} catch (e) { 3100 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); 3101} 3102``` 3103 3104### getEntries 3105 3106getEntries(query: Query, callback: AsyncCallback<Entry[]>): void 3107 3108Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result. 3109 3110**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3111 3112**Parameters** 3113 3114| Name | Type | Mandatory| Description | 3115| -------- | -------------------------------------- | ---- | ----------------------------------------------- | 3116| query | [Query](#query) | Yes | Key prefix to match. | 3117| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs that match the specified **Query** object.| 3118 3119**Error codes** 3120 3121For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3122 3123| ID| **Error Message** | 3124| ------------ | -------------------------------------- | 3125| 15100003 | Database corrupted. | 3126| 15100005 | Database or result set already closed. | 3127 3128**Example** 3129 3130```js 3131let kvStore; 3132try { 3133 var arr = new Uint8Array([21, 31]); 3134 let entries = []; 3135 for (var i = 0; i < 10; i++) { 3136 var key = 'batch_test_bool_key'; 3137 var entry = { 3138 key: key + i, 3139 value: { 3140 type: distributedKVStore.ValueType.BYTE_ARRAY, 3141 value: arr 3142 } 3143 } 3144 entries.push(entry); 3145 } 3146 console.info(`entries: {entries}`); 3147 kvStore.putBatch(entries, async function (err) { 3148 console.info('Succeeded in putting Batch'); 3149 const query = new distributedKVStore.Query(); 3150 query.prefixKey("batch_test"); 3151 kvStore.getEntries(query, function (err, entries) { 3152 if (err != undefined) { 3153 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 3154 return; 3155 } 3156 console.info('Succeeded in getting Entries'); 3157 console.info(`entries.length: ${entries.length}`); 3158 console.info(`entries[0]: ${entries[0]}`); 3159 }); 3160 }); 3161} catch (e) { 3162 console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`); 3163} 3164``` 3165 3166### getEntries 3167 3168getEntries(query: Query): Promise<Entry[]> 3169 3170Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result. 3171 3172**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3173 3174**Parameters** 3175 3176| Name| Type | Mandatory| Description | 3177| ------ | -------------- | ---- | -------------- | 3178| query | [Query](#query) | Yes | **Query** object to match.| 3179 3180**Return value** 3181 3182| Type | Description | 3183| -------------------------------- | -------------------------------------------------- | 3184| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified **Query** object.| 3185 3186**Error codes** 3187 3188For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3189 3190| ID| **Error Message** | 3191| ------------ | -------------------------------------- | 3192| 15100003 | Database corrupted. | 3193| 15100005 | Database or result set already closed. | 3194 3195**Example** 3196 3197```js 3198let kvStore; 3199try { 3200 var arr = new Uint8Array([21, 31]); 3201 let entries = []; 3202 for (var i = 0; i < 10; i++) { 3203 var key = 'batch_test_bool_key'; 3204 var entry = { 3205 key: key + i, 3206 value: { 3207 type: distributedKVStore.ValueType.BYTE_ARRAY, 3208 value: arr 3209 } 3210 } 3211 entries.push(entry); 3212 } 3213 console.info(`entries: {entries}`); 3214 kvStore.putBatch(entries).then(async () => { 3215 console.info('Succeeded in putting Batch'); 3216 const query = new distributedKVStore.Query(); 3217 query.prefixKey("batch_test"); 3218 kvStore.getEntries(query).then((entries) => { 3219 console.info('Succeeded in getting Entries'); 3220 }).catch((err) => { 3221 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 3222 }); 3223 }).catch((err) => { 3224 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`) 3225 }); 3226 console.info('Succeeded in getting Entries'); 3227} catch (e) { 3228 console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`); 3229} 3230``` 3231 3232### getResultSet 3233 3234getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void 3235 3236Obtains a result set with the specified prefix from this single KV store. This API uses an asynchronous callback to return the result. 3237 3238**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3239 3240**Parameters** 3241 3242| Name | Type | Mandatory| Description | 3243| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | 3244| keyPrefix | string | Yes | Key prefix to match. | 3245| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the result set with the specified prefix.| 3246 3247**Error codes** 3248 3249For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3250 3251| ID| **Error Message** | 3252| ------------ | -------------------------------------- | 3253| 15100003 | Database corrupted. | 3254| 15100005 | Database or result set already closed. | 3255 3256**Example** 3257 3258```js 3259let kvStore; 3260try { 3261 let resultSet; 3262 let entries = []; 3263 for (var i = 0; i < 10; i++) { 3264 var key = 'batch_test_string_key'; 3265 var entry = { 3266 key: key + i, 3267 value: { 3268 type: distributedKVStore.ValueType.STRING, 3269 value: 'batch_test_string_value' 3270 } 3271 } 3272 entries.push(entry); 3273 } 3274 kvStore.putBatch(entries, async function (err) { 3275 if (err != undefined) { 3276 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 3277 return; 3278 } 3279 console.info('Succeeded in putting batch'); 3280 kvStore.getResultSet('batch_test_string_key', async function (err, result) { 3281 if (err != undefined) { 3282 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3283 return; 3284 } 3285 console.info('Succeeded in getting result set'); 3286 resultSet = result; 3287 kvStore.closeResultSet(resultSet, function (err) { 3288 if (err != undefined) { 3289 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 3290 return; 3291 } 3292 console.info('Succeeded in closing result set'); 3293 }) 3294 }); 3295 }); 3296} catch (e) { 3297 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 3298} 3299``` 3300 3301### getResultSet 3302 3303getResultSet(keyPrefix: string): Promise<KVStoreResultSet> 3304 3305Obtains a result set with the specified prefix from this single KV store. This API uses a promise to return the result. 3306 3307**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3308 3309**Parameters** 3310 3311| Name | Type| Mandatory| Description | 3312| --------- | -------- | ---- | -------------------- | 3313| keyPrefix | string | Yes | Key prefix to match.| 3314 3315**Return value** 3316 3317| Type | Description | 3318| ---------------------------------------------------- | --------------------------------------- | 3319| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the result set with the specified prefix.| 3320 3321**Error codes** 3322 3323For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3324 3325| ID| **Error Message** | 3326| ------------ | -------------------------------------- | 3327| 15100003 | Database corrupted. | 3328| 15100005 | Database or result set already closed. | 3329 3330**Example** 3331 3332```js 3333let kvStore; 3334try { 3335 let resultSet; 3336 let entries = []; 3337 for (var i = 0; i < 10; i++) { 3338 var key = 'batch_test_string_key'; 3339 var entry = { 3340 key: key + i, 3341 value: { 3342 type: distributedKVStore.ValueType.STRING, 3343 value: 'batch_test_string_value' 3344 } 3345 } 3346 entries.push(entry); 3347 } 3348 kvStore.putBatch(entries).then(async () => { 3349 console.info('Succeeded in putting batch'); 3350 }).catch((err) => { 3351 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 3352 }); 3353 kvStore.getResultSet('batch_test_string_key').then((result) => { 3354 console.info('Succeeded in getting result set'); 3355 resultSet = result; 3356 }).catch((err) => { 3357 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3358 }); 3359 kvStore.closeResultSet(resultSet).then(() => { 3360 console.info('Succeeded in closing result set'); 3361 }).catch((err) => { 3362 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 3363 }); 3364} catch (e) { 3365 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 3366} 3367``` 3368 3369### getResultSet 3370 3371getResultSet(query: Query, callback: AsyncCallback<KVStoreResultSet>): void 3372 3373Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. 3374 3375**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3376 3377**Parameters** 3378 3379| Name | Type | Mandatory| Description | 3380| -------- | ---------------------------------------------------------- | ---- | --------------------------------------------------------- | 3381| query | Query | Yes | **Query** object to match. | 3382| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| 3383 3384**Error codes** 3385 3386For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3387 3388| ID| **Error Message** | 3389| ------------ | -------------------------------------- | 3390| 15100003 | Database corrupted. | 3391| 15100005 | Database or result set already closed. | 3392 3393**Example** 3394 3395```js 3396let kvStore; 3397try { 3398 let resultSet; 3399 let entries = []; 3400 for (var i = 0; i < 10; i++) { 3401 var key = 'batch_test_string_key'; 3402 var entry = { 3403 key: key + i, 3404 value: { 3405 type: distributedKVStore.ValueType.STRING, 3406 value: 'batch_test_string_value' 3407 } 3408 } 3409 entries.push(entry); 3410 } 3411 kvStore.putBatch(entries, async function (err) { 3412 if (err != undefined) { 3413 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 3414 return; 3415 } 3416 console.info('Succeeded in putting batch'); 3417 const query = new distributedKVStore.Query(); 3418 query.prefixKey("batch_test"); 3419 kvStore.getResultSet(query, async function (err, result) { 3420 if (err != undefined) { 3421 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3422 return; 3423 } 3424 console.info('Succeeded in getting result set'); 3425 }); 3426 }); 3427} catch (e) { 3428 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 3429} 3430``` 3431 3432### getResultSet 3433 3434getResultSet(query: Query): Promise<KVStoreResultSet> 3435 3436Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. 3437 3438**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3439 3440**Parameters** 3441 3442| Name| Type | Mandatory| Description | 3443| ------ | -------------- | ---- | -------------- | 3444| query | [Query](#query) | Yes | **Query** object to match.| 3445 3446**Return value** 3447 3448| Type | Description | 3449| ---------------------------------------------------- | ------------------------------------------------------------ | 3450| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| 3451 3452**Error codes** 3453 3454For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3455 3456| ID| **Error Message** | 3457| ------------ | -------------------------------------- | 3458| 15100003 | Database corrupted. | 3459| 15100005 | Database or result set already closed. | 3460 3461**Example** 3462 3463```js 3464let kvStore; 3465try { 3466 let resultSet; 3467 let entries = []; 3468 for (var i = 0; i < 10; i++) { 3469 var key = 'batch_test_string_key'; 3470 var entry = { 3471 key: key + i, 3472 value: { 3473 type: distributedKVStore.ValueType.STRING, 3474 value: 'batch_test_string_value' 3475 } 3476 } 3477 entries.push(entry); 3478 } 3479 kvStore.putBatch(entries).then(async () => { 3480 console.info('Succeeded in putting batch'); 3481 }).catch((err) => { 3482 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 3483 }); 3484 const query = new distributedKVStore.Query(); 3485 query.prefixKey("batch_test"); 3486 kvStore.getResultSet(query).then((result) => { 3487 console.info('Succeeded in getting result set'); 3488 resultSet = result; 3489 }).catch((err) => { 3490 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3491 }); 3492} catch (e) { 3493 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 3494} 3495``` 3496 3497### getResultSet 3498 3499getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void 3500 3501Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses an asynchronous callback to return the result. 3502 3503**System API**: This is a system API. 3504 3505**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 3506 3507**Parameters** 3508 3509| Name | Type | Mandatory| Description | 3510| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3511| 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. | 3512| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| 3513 3514**Error codes** 3515 3516For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3517 3518| ID| **Error Message** | 3519| ------------ | -------------------------------------- | 3520| 15100003 | Database corrupted. | 3521| 15100005 | Database or result set already closed. | 3522 3523**Example** 3524 3525```js 3526import dataSharePredicates from '@ohos.data.dataSharePredicates'; 3527 3528let kvStore; 3529try { 3530 let resultSet; 3531 let predicates = new dataSharePredicates.DataSharePredicates(); 3532 predicates.prefixKey("batch_test_string_key"); 3533 kvStore.getResultSet(predicates, async function (err, result) { 3534 if (err != undefined) { 3535 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3536 return; 3537 } 3538 console.info('Succeeded in getting result set'); 3539 resultSet = result; 3540 kvStore.closeResultSet(resultSet, function (err) { 3541 if (err != undefined) { 3542 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 3543 return; 3544 } 3545 console.info('Succeeded in closing result set'); 3546 }) 3547 }); 3548} catch (e) { 3549 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 3550} 3551``` 3552 3553### getResultSet 3554 3555getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> 3556 3557Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses a promise to return the result. 3558 3559**System API**: This is a system API. 3560 3561**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 3562 3563**Parameters** 3564 3565| Name | Type | Mandatory| Description | 3566| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | 3567| 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.| 3568 3569**Return value** 3570 3571| Type | Description | 3572| ---------------------------------------------------- | ------------------------- | 3573| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| 3574 3575**Error codes** 3576 3577For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3578 3579| ID| **Error Message** | 3580| ------------ | -------------------------------------- | 3581| 15100003 | Database corrupted. | 3582| 15100005 | Database or result set already closed. | 3583 3584**Example** 3585 3586```js 3587import dataSharePredicates from '@ohos.data.dataSharePredicates'; 3588 3589let kvStore; 3590try { 3591 let resultSet; 3592 let predicates = new dataSharePredicates.DataSharePredicates(); 3593 predicates.prefixKey("batch_test_string_key"); 3594 kvStore.getResultSet(predicates).then((result) => { 3595 console.info('Succeeded in getting result set'); 3596 resultSet = result; 3597 }).catch((err) => { 3598 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3599 }); 3600 kvStore.closeResultSet(resultSet).then(() => { 3601 console.info('Succeeded in closing result set'); 3602 }).catch((err) => { 3603 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 3604 }); 3605} catch (e) { 3606 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 3607} 3608``` 3609 3610### closeResultSet 3611 3612closeResultSet(resultSet: KVStoreResultSet, callback: AsyncCallback<void>): void 3613 3614Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). This API uses an asynchronous callback to return the result. 3615 3616**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3617 3618**Parameters** 3619 3620| Name | Type | Mandatory| Description | 3621| --------- | ------------------------------------- | ---- | ---------------------------------- | 3622| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes | **KVStoreResultSet** object to close.| 3623| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 3624 3625**Example** 3626 3627```js 3628let kvStore; 3629try { 3630 let resultSet = null; 3631 kvStore.closeResultSet(resultSet, function (err) { 3632 if (err == undefined) { 3633 console.info('Succeeded in closing result set'); 3634 } else { 3635 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 3636 } 3637 }); 3638} catch (e) { 3639 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 3640} 3641``` 3642 3643### closeResultSet 3644 3645closeResultSet(resultSet: KVStoreResultSet): Promise<void> 3646 3647Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). This API uses a promise to return the result. 3648 3649**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3650 3651**Parameters** 3652 3653| Name | Type | Mandatory| Description | 3654| --------- | ------------------------------------- | ---- | ---------------------------------- | 3655| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes | **KVStoreResultSet** object to close.| 3656 3657**Return value** 3658 3659| Type | Description | 3660| ------------------- | ------------------------- | 3661| Promise<void> | Promise that returns no value.| 3662 3663**Example** 3664 3665```js 3666let kvStore; 3667try { 3668 let resultSet = null; 3669 kvStore.closeResultSet(resultSet).then(() => { 3670 console.info('Succeeded in closing result set'); 3671 }).catch((err) => { 3672 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 3673 }); 3674} catch (e) { 3675 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 3676} 3677``` 3678 3679### getResultSize 3680 3681getResultSize(query: Query, callback: AsyncCallback<number>): void 3682 3683Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result. 3684 3685**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3686 3687**Parameters** 3688 3689| Name | Type | Mandatory| Description | 3690| -------- | --------------------------- | ---- | ------------------------------------------- | 3691| query | [Query](#query) | Yes | **Query** object to match. | 3692| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| 3693 3694**Error codes** 3695 3696For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3697 3698| ID| **Error Message** | 3699| ------------ | -------------------------------------- | 3700| 15100003 | Database corrupted. | 3701| 15100005 | Database or result set already closed. | 3702 3703**Example** 3704 3705```js 3706let kvStore; 3707try { 3708 let entries = []; 3709 for (var i = 0; i < 10; i++) { 3710 var key = 'batch_test_string_key'; 3711 var entry = { 3712 key: key + i, 3713 value: { 3714 type: distributedKVStore.ValueType.STRING, 3715 value: 'batch_test_string_value' 3716 } 3717 } 3718 entries.push(entry); 3719 } 3720 kvStore.putBatch(entries, async function (err) { 3721 console.info('Succeeded in putting batch'); 3722 const query = new distributedKVStore.Query(); 3723 query.prefixKey("batch_test"); 3724 kvStore.getResultSize(query, async function (err, resultSize) { 3725 if (err != undefined) { 3726 console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); 3727 return; 3728 } 3729 console.info('Succeeded in getting result set size'); 3730 }); 3731 }); 3732} catch (e) { 3733 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 3734} 3735``` 3736 3737### getResultSize 3738 3739getResultSize(query: Query): Promise<number> 3740 3741Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result. 3742 3743**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3744 3745**Parameters** 3746 3747| Name| Type | Mandatory| Description | 3748| ------ | -------------- | ---- | -------------- | 3749| query | [Query](#query) | Yes | **Query** object to match.| 3750 3751**Return value** 3752 3753| Type | Description | 3754| --------------------- | ----------------------------------------------- | 3755| Promise<number> | Promise used to return the number of results obtained.| 3756 3757**Error codes** 3758 3759For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3760 3761| ID| **Error Message** | 3762| ------------ | -------------------------------------- | 3763| 15100003 | Database corrupted. | 3764| 15100005 | Database or result set already closed. | 3765 3766**Example** 3767 3768```js 3769let kvStore; 3770try { 3771 let entries = []; 3772 for (var i = 0; i < 10; i++) { 3773 var key = 'batch_test_string_key'; 3774 var entry = { 3775 key: key + i, 3776 value: { 3777 type: distributedKVStore.ValueType.STRING, 3778 value: 'batch_test_string_value' 3779 } 3780 } 3781 entries.push(entry); 3782 } 3783 kvStore.putBatch(entries).then(async () => { 3784 console.info('Succeeded in putting batch'); 3785 }).catch((err) => { 3786 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 3787 }); 3788 const query = new distributedKVStore.Query(); 3789 query.prefixKey("batch_test"); 3790 kvStore.getResultSize(query).then((resultSize) => { 3791 console.info('Succeeded in getting result set size'); 3792 }).catch((err) => { 3793 console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); 3794 }); 3795} catch (e) { 3796 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 3797} 3798``` 3799 3800### backup 3801 3802backup(file:string, callback: AsyncCallback<void>):void 3803 3804Backs up a distributed KV store. This API uses an asynchronous callback to return the result. 3805 3806**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3807 3808**Parameters** 3809 3810| Name | Type | Mandatory| Description | 3811| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 3812| file | string | Yes | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 3813| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3814 3815**Error codes** 3816 3817For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3818 3819| ID| **Error Message** | 3820| ------------ | -------------------------------------- | 3821| 15100005 | Database or result set already closed. | 3822 3823**Example** 3824 3825```js 3826let kvStore; 3827let file = "BK001"; 3828try { 3829 kvStore.backup(file, (err) => { 3830 if (err) { 3831 console.error(`Failed to backup.code is ${err.code},message is ${err.message} `); 3832 } else { 3833 console.info(`Succeeded in backupping data`); 3834 } 3835 }); 3836} catch (e) { 3837 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 3838} 3839``` 3840 3841### backup 3842 3843backup(file:string): Promise<void> 3844 3845Backs up an RDB store. This API uses a promise to return the result. 3846 3847**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3848 3849**Parameters** 3850 3851| Name| Type| Mandatory| Description | 3852| ------ | -------- | ---- | ------------------------------------------------------------ | 3853| file | string | Yes | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 3854 3855**Return value** 3856 3857| Type | Description | 3858| ------------------- | ------------------------- | 3859| Promise<void> | Promise that returns no value.| 3860 3861**Error codes** 3862 3863For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3864 3865| ID| **Error Message** | 3866| ------------ | -------------------------------------- | 3867| 15100005 | Database or result set already closed. | 3868 3869**Example** 3870 3871```js 3872let kvStore; 3873let file = "BK001"; 3874try { 3875 kvStore.backup(file).then(() => { 3876 console.info(`Succeeded in backupping data`); 3877 }).catch((err) => { 3878 console.error(`Failed to backup.code is ${err.code},message is ${err.message}`); 3879 }); 3880} catch (e) { 3881 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 3882} 3883``` 3884 3885### restore 3886 3887restore(file:string, callback: AsyncCallback<void>):void 3888 3889Restores a distributed KV store from a database file. This API uses an asynchronous callback to return the result. 3890 3891**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3892 3893**Parameters** 3894 3895| Name | Type | Mandatory| Description | 3896| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 3897| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 3898| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 3899 3900**Error codes** 3901 3902For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3903 3904| ID| **Error Message** | 3905| ------------ | -------------------------------------- | 3906| 15100005 | Database or result set already closed. | 3907 3908**Example** 3909 3910```js 3911let kvStore; 3912let file = "BK001"; 3913try { 3914 kvStore.restore(file, (err) => { 3915 if (err) { 3916 console.error(`Failed to restore.code is ${err.code},message is ${err.message}`); 3917 } else { 3918 console.info(`Succeeded in restoring data`); 3919 } 3920 }); 3921} catch (e) { 3922 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 3923} 3924``` 3925 3926### restore 3927 3928restore(file:string): Promise<void> 3929 3930Restores a distributed KV store from a database file. This API uses a promise to return the result. 3931 3932**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3933 3934**Parameters** 3935 3936| Name| Type| Mandatory| Description | 3937| ------ | -------- | ---- | ------------------------------------------------------------ | 3938| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 3939 3940**Return value** 3941 3942| Type | Description | 3943| ------------------- | ------------------------- | 3944| Promise<void> | Promise that returns no value.| 3945 3946**Error codes** 3947 3948For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3949 3950| ID| **Error Message** | 3951| ------------ | -------------------------------------- | 3952| 15100005 | Database or result set already closed. | 3953 3954**Example** 3955 3956```js 3957let kvStore; 3958let file = "BK001"; 3959try { 3960 kvStore.restore(file).then(() => { 3961 console.info(`Succeeded in restoring data`); 3962 }).catch((err) => { 3963 console.error(`Failed to restore.code is ${err.code},message is ${err.message}`); 3964 }); 3965} catch (e) { 3966 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 3967} 3968``` 3969 3970### deleteBackup 3971 3972deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[string, number]>>):void 3973 3974Deletes a backup file. This API uses an asynchronous callback to return the result. 3975 3976**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3977 3978**Parameters** 3979 3980| Name | Type | Mandatory| Description | 3981| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | 3982| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 3983| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to return the name of the backup file deleted and the operation result. | 3984 3985**Example** 3986 3987```js 3988let kvStore; 3989let files = ["BK001", "BK002"]; 3990try { 3991 kvStore.deleteBackup(files, (err, data) => { 3992 if (err) { 3993 console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`); 3994 } else { 3995 console.info(`Succeed in deleting Backup.data=${data}`); 3996 } 3997 }); 3998} catch (e) { 3999 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4000} 4001``` 4002 4003### deleteBackup 4004 4005deleteBackup(files:Array<string>): Promise<Array<[string, number]>> 4006 4007Deletes a backup file. This API uses a promise to return the result. 4008 4009**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4010 4011**Parameters** 4012 4013| Name| Type | Mandatory| Description | 4014| ------ | ------------------- | ---- | ------------------------------------------------------------ | 4015| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 4016 4017**Return value** 4018 4019| Type | Description | 4020| -------------------------------------------- | ----------------------------------------------- | 4021| Promise<Array<[string, number]>> | Promise used to return the name of the backup file deleted and the operation result.| 4022 4023**Example** 4024 4025```js 4026let kvStore; 4027let files = ["BK001", "BK002"]; 4028try { 4029 kvStore.deleteBackup(files).then((data) => { 4030 console.info(`Succeed in deleting Backup.data=${data}`); 4031 }).catch((err) => { 4032 console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`); 4033 }) 4034} catch (e) { 4035 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4036} 4037``` 4038 4039### startTransaction 4040 4041startTransaction(callback: AsyncCallback<void>): void 4042 4043Starts the transaction in this single KV store. This API uses an asynchronous callback to return the result. 4044 4045**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4046 4047**Parameters** 4048 4049| Name | Type | Mandatory| Description | 4050| -------- | ------------------------- | ---- | ---------- | 4051| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| 4052 4053**Error codes** 4054 4055For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4056 4057| ID| **Error Message** | 4058| ------------ | -------------------------------------- | 4059| 15100005 | Database or result set already closed. | 4060 4061**Example** 4062 4063```js 4064let kvStore; 4065function putBatchString(len, prefix) { 4066 let entries = []; 4067 for (var i = 0; i < len; i++) { 4068 var entry = { 4069 key: prefix + i, 4070 value: { 4071 type: distributedKVStore.ValueType.STRING, 4072 value: 'batch_test_string_value' 4073 } 4074 } 4075 entries.push(entry); 4076 } 4077 return entries; 4078} 4079 4080try { 4081 var count = 0; 4082 kvStore.on('dataChange', 0, function (data) { 4083 console.info(`startTransaction 0 ${data}`); 4084 count++; 4085 }); 4086 kvStore.startTransaction(async function (err) { 4087 if (err != undefined) { 4088 console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`); 4089 return; 4090 } 4091 console.info('Succeeded in starting Transaction'); 4092 let entries = putBatchString(10, 'batch_test_string_key'); 4093 console.info(`entries: ${entries}`); 4094 kvStore.putBatch(entries, async function (err) { 4095 if (err != undefined) { 4096 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 4097 return; 4098 } 4099 console.info('Succeeded in putting Batch'); 4100 }); 4101 }); 4102} catch (e) { 4103 console.error(`Failed to start Transaction.code is ${e.code},message is ${e.message}`); 4104} 4105``` 4106 4107### startTransaction 4108 4109startTransaction(): Promise<void> 4110 4111Starts the transaction in this single KV store. This API uses a promise to return the result. 4112 4113**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4114 4115**Return value** 4116 4117| Type | Description | 4118| ------------------- | ------------------------- | 4119| Promise<void> | Promise that returns no value.| 4120 4121**Error codes** 4122 4123For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4124 4125| ID| **Error Message** | 4126| ------------ | -------------------------------------- | 4127| 15100005 | Database or result set already closed. | 4128 4129**Example** 4130 4131```js 4132let kvStore; 4133try { 4134 var count = 0; 4135 kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { 4136 console.info(`startTransaction 0 ${data}`); 4137 count++; 4138 }); 4139 kvStore.startTransaction().then(async () => { 4140 console.info('Succeeded in starting Transaction'); 4141 }).catch((err) => { 4142 console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`); 4143 }); 4144} catch (e) { 4145 console.error(`Failed to start Transaction.code is ${e.code},message is ${e.message}`); 4146} 4147``` 4148 4149### commit 4150 4151commit(callback: AsyncCallback<void>): void 4152 4153Commits the transaction in this single KV store. This API uses an asynchronous callback to return the result. 4154 4155**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4156 4157**Parameters** 4158 4159| Name | Type | Mandatory| Description | 4160| -------- | ------------------------- | ---- | ---------- | 4161| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| 4162 4163**Error codes** 4164 4165For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4166 4167| ID| **Error Message** | 4168| ------------ | -------------------------------------- | 4169| 15100005 | Database or result set already closed. | 4170 4171**Example** 4172 4173```js 4174let kvStore; 4175try { 4176 kvStore.commit(function (err) { 4177 if (err == undefined) { 4178 console.info('Succeeded in committing'); 4179 } else { 4180 console.error(`Failed to commit.code is ${err.code},message is ${err.message}`); 4181 } 4182 }); 4183} catch (e) { 4184 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4185} 4186``` 4187 4188### commit 4189 4190commit(): Promise<void> 4191 4192Commits the transaction in this single KV store. This API uses a promise to return the result. 4193 4194**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4195 4196**Return value** 4197 4198| Type | Description | 4199| ------------------- | ------------------------- | 4200| Promise<void> | Promise that returns no value.| 4201 4202**Error codes** 4203 4204For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4205 4206| ID| **Error Message** | 4207| ------------ | -------------------------------------- | 4208| 15100005 | Database or result set already closed. | 4209 4210**Example** 4211 4212```js 4213let kvStore; 4214try { 4215 kvStore.commit().then(async () => { 4216 console.info('Succeeded in committing'); 4217 }).catch((err) => { 4218 console.error(`Failed to commit.code is ${err.code},message is ${err.message}`); 4219 }); 4220} catch (e) { 4221 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4222} 4223``` 4224 4225### rollback 4226 4227rollback(callback: AsyncCallback<void>): void 4228 4229Rolls back the transaction in this single KV store. This API uses an asynchronous callback to return the result. 4230 4231**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4232 4233**Parameters** 4234 4235| Name | Type | Mandatory| Description | 4236| -------- | ------------------------- | ---- | ---------- | 4237| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| 4238 4239**Error codes** 4240 4241For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4242 4243| ID| **Error Message** | 4244| ------------ | -------------------------------------- | 4245| 15100005 | Database or result set already closed. | 4246 4247**Example** 4248 4249```js 4250let kvStore; 4251try { 4252 kvStore.rollback(function (err) { 4253 if (err == undefined) { 4254 console.info('Succeeded in rolling back'); 4255 } else { 4256 console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`); 4257 } 4258 }); 4259}catch(e) { 4260 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4261} 4262``` 4263 4264### rollback 4265 4266rollback(): Promise<void> 4267 4268Rolls back the transaction in this single KV store. This API uses a promise to return the result. 4269 4270**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4271 4272**Return value** 4273 4274| Type | Description | 4275| ------------------- | ------------------------- | 4276| Promise<void> | Promise that returns no value.| 4277 4278**Error codes** 4279 4280For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4281 4282| ID| **Error Message** | 4283| ------------ | -------------------------------------- | 4284| 15100005 | Database or result set already closed. | 4285 4286**Example** 4287 4288```js 4289let kvStore; 4290try { 4291 kvStore.rollback().then(async () => { 4292 console.info('Succeeded in rolling back'); 4293 }).catch((err) => { 4294 console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`); 4295 }); 4296} catch (e) { 4297 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4298} 4299``` 4300 4301### enableSync 4302 4303enableSync(enabled: boolean, callback: AsyncCallback<void>): void 4304 4305Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result. 4306 4307**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4308 4309**Parameters** 4310 4311| Name | Type | Mandatory| Description | 4312| -------- | ------------------------- | ---- | --------------------------------------------------------- | 4313| enabled | boolean | Yes | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.| 4314| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 4315 4316**Example** 4317 4318```js 4319let kvStore; 4320try { 4321 kvStore.enableSync(true, function (err) { 4322 if (err == undefined) { 4323 console.info('Succeeded in enabling sync'); 4324 } else { 4325 console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`); 4326 } 4327 }); 4328} catch (e) { 4329 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4330} 4331``` 4332 4333### enableSync 4334 4335enableSync(enabled: boolean): Promise<void> 4336 4337Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result. 4338 4339**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4340 4341**Parameters** 4342 4343| Name | Type| Mandatory| Description | 4344| ------- | -------- | ---- | --------------------------------------------------------- | 4345| enabled | boolean | Yes | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.| 4346 4347**Return value** 4348 4349| Type | Description | 4350| ------------------- | ------------------------- | 4351| Promise<void> | Promise that returns no value.| 4352 4353**Example** 4354 4355```js 4356let kvStore; 4357try { 4358 kvStore.enableSync(true).then(() => { 4359 console.info('Succeeded in enabling sync'); 4360 }).catch((err) => { 4361 console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`); 4362 }); 4363} catch (e) { 4364 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4365} 4366``` 4367 4368### setSyncRange 4369 4370setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void 4371 4372Sets the data synchronization range. This API uses an asynchronous callback to return the result. 4373 4374**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4375 4376**Parameters** 4377 4378| Name | Type | Mandatory| Description | 4379| ------------------- | ------------------------- | ---- | -------------------------------- | 4380| localLabels | string[] | Yes | Synchronization labels set for the local device. | 4381| remoteSupportLabels | string[] | Yes | Synchronization labels set for remote devices.| 4382| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 4383 4384**Example** 4385 4386```js 4387let kvStore; 4388try { 4389 const localLabels = ['A', 'B']; 4390 const remoteSupportLabels = ['C', 'D']; 4391 kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err) { 4392 if (err != undefined) { 4393 console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`); 4394 return; 4395 } 4396 console.info('Succeeded in setting syncRange'); 4397 }); 4398} catch (e) { 4399 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4400} 4401``` 4402 4403### setSyncRange 4404 4405setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void> 4406 4407Sets the data synchronization range. This API uses a promise to return the result. 4408 4409**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4410 4411**Parameters** 4412 4413| Name | Type| Mandatory| Description | 4414| ------------------- | -------- | ---- | -------------------------------- | 4415| localLabels | string[] | Yes | Synchronization labels set for the local device. | 4416| remoteSupportLabels | string[] | Yes | Synchronization labels set for remote devices.| 4417 4418**Return value** 4419 4420| Type | Description | 4421| ------------------- | ------------------------- | 4422| Promise<void> | Promise that returns no value.| 4423 4424**Example** 4425 4426```js 4427let kvStore; 4428try { 4429 const localLabels = ['A', 'B']; 4430 const remoteSupportLabels = ['C', 'D']; 4431 kvStore.setSyncRange(localLabels, remoteSupportLabels).then(() => { 4432 console.info('Succeeded in setting syncRange'); 4433 }).catch((err) => { 4434 console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`); 4435 }); 4436} catch (e) { 4437 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4438} 4439``` 4440 4441### setSyncParam 4442 4443setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void 4444 4445Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result. 4446 4447**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4448 4449**Parameters** 4450 4451| Name | Type | Mandatory| Description | 4452| --------------------- | ------------------------- | ---- | -------------------------------------------- | 4453| defaultAllowedDelayMs | number | Yes | Default delay allowed for database synchronization, in ms.| 4454| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 4455 4456**Example** 4457 4458```js 4459let kvStore; 4460try { 4461 const defaultAllowedDelayMs = 500; 4462 kvStore.setSyncParam(defaultAllowedDelayMs, function (err) { 4463 if (err != undefined) { 4464 console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`); 4465 return; 4466 } 4467 console.info('Succeeded in setting syncParam'); 4468 }); 4469} catch (e) { 4470 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4471} 4472``` 4473 4474### setSyncParam 4475 4476setSyncParam(defaultAllowedDelayMs: number): Promise<void> 4477 4478Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result. 4479 4480**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4481 4482**Parameters** 4483 4484| Name | Type| Mandatory| Description | 4485| --------------------- | -------- | ---- | -------------------------------------------- | 4486| defaultAllowedDelayMs | number | Yes | Default delay allowed for database synchronization, in ms.| 4487 4488**Return value** 4489 4490| Type | Description | 4491| ------------------- | ------------------------- | 4492| Promise<void> | Promise that returns no value.| 4493 4494**Example** 4495 4496```js 4497let kvStore; 4498try { 4499 const defaultAllowedDelayMs = 500; 4500 kvStore.setSyncParam(defaultAllowedDelayMs).then(() => { 4501 console.info('Succeeded in setting syncParam'); 4502 }).catch((err) => { 4503 console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`); 4504 }); 4505} catch (e) { 4506 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4507} 4508``` 4509 4510### sync 4511 4512sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void 4513 4514Synchronizes 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). 4515> **NOTE** 4516> 4517> 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. 4518 4519**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 4520 4521**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4522 4523**Parameters** 4524 4525| Name | Type | Mandatory| Description | 4526| --------- | --------------------- | ---- | ---------------------------------------------- | 4527| deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| 4528| mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | 4529| delayMs | number | No | Allowed synchronization delay time, in ms. The default value is **0**. | 4530 4531**Error codes** 4532 4533For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4534 4535| ID| **Error Message** | 4536| ------------ | ------------------- | 4537| 15100003 | Database corrupted. | 4538| 15100004 | Not found. | 4539 4540**Example** 4541 4542```js 4543import deviceManager from '@ohos.distributedHardware.deviceManager'; 4544 4545let devManager; 4546let kvStore; 4547const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; 4548const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; 4549// create deviceManager 4550deviceManager.createDeviceManager('bundleName', (err, value) => { 4551 if (!err) { 4552 devManager = value; 4553 let deviceIds = []; 4554 if (devManager != null) { 4555 var devices = devManager.getTrustedDeviceListSync(); 4556 for (var i = 0; i < devices.length; i++) { 4557 deviceIds[i] = devices[i].deviceId; 4558 } 4559 } 4560 try { 4561 kvStore.on('syncComplete', function (data) { 4562 console.info('Sync dataChange'); 4563 }); 4564 kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { 4565 if (err != undefined) { 4566 console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); 4567 return; 4568 } 4569 console.info('Succeeded in putting data'); 4570 const mode = distributedKVStore.SyncMode.PULL_ONLY; 4571 kvStore.sync(deviceIds, mode, 1000); 4572 }); 4573 } catch (e) { 4574 console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); 4575 } 4576 } 4577}); 4578``` 4579 4580### sync 4581 4582sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void 4583 4584Synchronizes 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). 4585> **NOTE** 4586> 4587> 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. 4588 4589**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 4590 4591**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4592 4593**Parameters** 4594 4595| Name | Type | Mandatory| Description | 4596| --------- | --------------------- | ---- | ---------------------------------------------- | 4597| deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| 4598| mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | 4599| query | [Query](#query) | Yes | **Query** object to match. | 4600| delayMs | number | No | Allowed synchronization delay time, in ms. The default value is **0**. | 4601 4602**Error codes** 4603 4604For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4605 4606| ID| **Error Message** | 4607| ------------ | ------------------- | 4608| 15100003 | Database corrupted. | 4609| 15100004 | Not found. | 4610 4611**Example** 4612 4613```js 4614import deviceManager from '@ohos.distributedHardware.deviceManager'; 4615 4616let devManager; 4617let kvStore; 4618const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; 4619const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; 4620// create deviceManager 4621deviceManager.createDeviceManager('bundleName', (err, value) => { 4622 if (!err) { 4623 devManager = value; 4624 let deviceIds = []; 4625 if (devManager != null) { 4626 var devices = devManager.getTrustedDeviceListSync(); 4627 for (var i = 0; i < devices.length; i++) { 4628 deviceIds[i] = devices[i].deviceId; 4629 } 4630 } 4631 try { 4632 kvStore.on('syncComplete', function (data) { 4633 console.info('Sync dataChange'); 4634 }); 4635 kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err) { 4636 if (err != undefined) { 4637 console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); 4638 return; 4639 } 4640 console.info('Succeeded in putting data'); 4641 const mode = distributedKVStore.SyncMode.PULL_ONLY; 4642 const query = new distributedKVStore.Query(); 4643 query.prefixKey("batch_test"); 4644 query.deviceId('localDeviceId'); 4645 kvStore.sync(deviceIds, query, mode, 1000); 4646 }); 4647 } catch (e) { 4648 console.error(`Failed to sync.code is ${e.code},message is ${e.message}`); 4649 } 4650 } 4651}); 4652``` 4653 4654### on('dataChange') 4655 4656on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void 4657 4658Subscribes to data changes of the specified type. 4659 4660**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4661 4662**Parameters** 4663 4664| Name | Type | Mandatory| Description | 4665| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | 4666| event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| 4667| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | 4668| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the data change. | 4669 4670**Error codes** 4671 4672For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4673 4674| ID| **Error Message** | 4675| ------------ | -------------------------------------- | 4676| 15100001 | Over max subscribe limits. | 4677| 15100005 | Database or result set already closed. | 4678 4679**Example** 4680 4681```js 4682let kvStore; 4683try { 4684 kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { 4685 console.info(`dataChange callback call data: ${data}`); 4686 }); 4687} catch (e) { 4688 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4689} 4690``` 4691 4692### on('syncComplete') 4693 4694on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void 4695 4696Subscribes to synchronization complete events. 4697 4698**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4699 4700**Parameters** 4701 4702| Name | Type | Mandatory| Description | 4703| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | 4704| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| 4705| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return the synchronization complete event. | 4706 4707**Example** 4708 4709```js 4710let kvStore; 4711const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; 4712const VALUE_TEST_FLOAT_ELEMENT = 321.12; 4713try { 4714 kvStore.on('syncComplete', function (data) { 4715 console.info(`syncComplete ${data}`); 4716 }); 4717 kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then(() => { 4718 console.info('succeeded in putting'); 4719 }).catch((err) => { 4720 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 4721 }); 4722} catch (e) { 4723 console.error(`Failed to subscribe syncComplete.code is ${e.code},message is ${e.message}`); 4724} 4725``` 4726 4727### off('dataChange') 4728 4729off(event:'dataChange', listener?: Callback<ChangeNotification>): void 4730 4731Unsubscribes from data changes. 4732 4733**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4734 4735**Parameters** 4736 4737| Name | Type | Mandatory| Description | 4738| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | 4739| event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| 4740| listener | Callback<[ChangeNotification](#changenotification)> | No | Callback for data changes. If the callback is not specified, all subscriptions to the data change event will be canceled. | 4741 4742**Error codes** 4743 4744For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4745 4746| ID| **Error Message** | 4747| ------------ | -------------------------------------- | 4748| 15100005 | Database or result set already closed. | 4749 4750**Example** 4751 4752```js 4753let kvStore; 4754class KvstoreModel { 4755 call(data) { 4756 console.info(`dataChange : ${data}`); 4757 } 4758 4759 subscribeDataChange() { 4760 try { 4761 if (kvStore != null) { 4762 kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); 4763 } 4764 } catch (err) { 4765 console.error(`Failed to subscribeDataChange.code is ${err.code},message is ${err.message}`); 4766 } 4767 } 4768 4769 unsubscribeDataChange() { 4770 try { 4771 if (kvStore != null) { 4772 kvStore.off('dataChange', this.call); 4773 } 4774 } catch (err) { 4775 console.error(`Failed to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); 4776 } 4777 } 4778} 4779``` 4780 4781### off('syncComplete') 4782 4783off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void 4784 4785Unsubscribes from synchronization complete events. 4786 4787**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4788 4789**Parameters** 4790 4791| Name | Type | Mandatory| Description | 4792| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | 4793| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| 4794| syncCallback | Callback<Array<[string, number]>> | No | Callback for the synchronization complete event. If the callback is not specified, all subscriptions to the synchronization complete event will be canceled. | 4795 4796**Example** 4797 4798```js 4799let kvStore; 4800class KvstoreModel { 4801 call(data) { 4802 console.info(`syncComplete : ${data}`); 4803 } 4804 4805 subscribeDataChange() { 4806 try { 4807 if (kvStore != null) { 4808 kvStore.on('syncComplete', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); 4809 } 4810 } catch (err) { 4811 console.error(`Failed to subscribeDataChange.code is ${err.code},message is ${err.message}`); 4812 } 4813 } 4814 4815 unsubscribeDataChange() { 4816 try { 4817 if (kvStore != null) { 4818 kvStore.off('dsyncComplete', this.call); 4819 } 4820 } catch (err) { 4821 console.error(`Failed to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); 4822 } 4823 } 4824} 4825``` 4826 4827### getSecurityLevel 4828 4829getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void 4830 4831Obtains the security level of this KV store. This API uses an asynchronous callback to return the result. 4832 4833**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4834 4835**Parameters** 4836 4837| Name | Type | Mandatory| Description | 4838| -------- | ---------------------------------------------------- | ---- | -------------------------------- | 4839| callback | AsyncCallback<[SecurityLevel](#securitylevel)> | Yes | Callback invoked to return the security level obtained.| 4840 4841**Error codes** 4842 4843For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4844 4845| ID| **Error Message** | 4846| ------------ | -------------------------------------- | 4847| 15100005 | Database or result set already closed. | 4848 4849**Example** 4850 4851```js 4852let kvStore; 4853try { 4854 kvStore.getSecurityLevel(function (err, data) { 4855 if (err != undefined) { 4856 console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`); 4857 return; 4858 } 4859 console.info('Succeeded in getting securityLevel'); 4860 }); 4861} catch (e) { 4862 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4863} 4864``` 4865 4866### getSecurityLevel 4867 4868getSecurityLevel(): Promise<SecurityLevel> 4869 4870Obtains the security level of this KV store. This API uses a promise to return the result. 4871 4872**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4873 4874**Return value** 4875 4876| Type | Description | 4877| ---------------------------------------------- | ----------------------------------- | 4878| Promise<[SecurityLevel](#securitylevel)> | Promise used to return the security level obtained.| 4879 4880**Error codes** 4881 4882For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4883 4884| ID| **Error Message** | 4885| ------------ | -------------------------------------- | 4886| 15100005 | Database or result set already closed. | 4887 4888**Example** 4889 4890```js 4891let kvStore; 4892try { 4893 kvStore.getSecurityLevel().then((data) => { 4894 console.info('Succeeded in getting securityLevel'); 4895 }).catch((err) => { 4896 console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`); 4897 }); 4898} catch (e) { 4899 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 4900} 4901``` 4902 4903## DeviceKVStore 4904 4905Provides APIs for querying and synchronizing data in a device KV store. This class inherits from **SingleKVStore**. 4906 4907Data 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. 4908 4909For 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. 4910 4911Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. 4912 4913### get 4914 4915get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 4916 4917Obtains the value of the specified key for this device. This API uses an asynchronous callback to return the result. 4918 4919**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4920 4921**Parameters** 4922 4923| Name | Type | Mandatory| Description | 4924| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 4925| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 4926| callback | AsyncCallback<boolean \| string \| number \| Uint8Array> | Yes | Callback invoked to return the value obtained. | 4927 4928**Error codes** 4929 4930For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4931 4932| ID| **Error Message** | 4933| ------------ | -------------------------------------- | 4934| 15100003 | Database corrupted. | 4935| 15100004 | Not found. | 4936| 15100005 | Database or result set already closed. | 4937 4938**Example** 4939 4940```js 4941let kvStore; 4942const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 4943const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 4944try { 4945 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err) { 4946 if (err != undefined) { 4947 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 4948 return; 4949 } 4950 console.info("Succeeded in putting"); 4951 kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { 4952 if (err != undefined) { 4953 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 4954 return; 4955 } 4956 console.info(`Succeeded in getting data.data=${data}`); 4957 }); 4958 }); 4959} catch (e) { 4960 console.error(`Failed to get.code is ${e.code},message is ${e.message}`); 4961} 4962``` 4963 4964### get 4965 4966get(key: string): Promise<boolean | string | number | Uint8Array> 4967 4968Obtains the value of the specified key for this device. This API uses a promise to return the result. 4969 4970**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4971 4972**Parameters** 4973 4974| Name| Type | Mandatory| Description | 4975| ------ | ------ | ---- | ------------------------------------------------------------ | 4976| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 4977 4978**Return value** 4979 4980| Type | Description | 4981| -------------------------------------------------------- | ------------------------------- | 4982| Promise<Uint8Array \| string \| boolean \| number> | Promise used to return the value obtained.| 4983 4984**Error codes** 4985 4986For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4987 4988| ID| **Error Message** | 4989| ------------ | -------------------------------------- | 4990| 15100003 | Database corrupted. | 4991| 15100004 | Not found. | 4992| 15100005 | Database or result set already closed. | 4993 4994**Example** 4995 4996```js 4997let kvStore; 4998const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 4999const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 5000try { 5001 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { 5002 console.info(`Succeeded in putting data`); 5003 kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { 5004 console.info(`Succeeded in getting data.data=${data}`); 5005 }).catch((err) => { 5006 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 5007 }); 5008 }).catch((err) => { 5009 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 5010 }); 5011} catch (e) { 5012 console.error(`Failed to get.code is ${e.code},message is ${e.message}`); 5013} 5014``` 5015 5016### get 5017 5018get(deviceId: string, key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 5019 5020Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. 5021 5022**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5023 5024**Parameters** 5025 5026| Name | Type| Mandatory | Description | 5027| ----- | ------ | ---- | ----------------------- | 5028| deviceId |string | Yes |ID of the target device. | 5029| key |string | Yes |Key to match. | 5030| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback invoked to return the value obtained. | 5031 5032**Error codes** 5033 5034For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5035 5036| ID| **Error Message** | 5037| ------------ | -------------------------------------- | 5038| 15100003 | Database corrupted. | 5039| 15100004 | Not found. | 5040| 15100005 | Database or result set already closed. | 5041 5042**Example** 5043 5044```js 5045let kvStore; 5046const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 5047const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; 5048try { 5049 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err) { 5050 if (err != undefined) { 5051 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 5052 return; 5053 } 5054 console.info('Succeeded in putting'); 5055 kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err, data) { 5056 if (err != undefined) { 5057 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 5058 return; 5059 } 5060 console.info('Succeeded in getting'); 5061 }); 5062 }) 5063} catch (e) { 5064 console.error(`Failed to get.code is ${e.code},message is ${e.message}`); 5065} 5066``` 5067 5068### get 5069 5070get(deviceId: string, key: string): Promise<boolean | string | number | Uint8Array> 5071 5072Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. 5073 5074**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5075 5076**Parameters** 5077 5078| Name | Type| Mandatory| Description | 5079| -------- | -------- | ---- | ------------------------ | 5080| deviceId | string | Yes | ID of the target device.| 5081| key | string | Yes | Key to match. | 5082 5083**Return value** 5084 5085| Type | Description | 5086| ------ | ------- | 5087|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value that matches the given condition.| 5088 5089**Error codes** 5090 5091For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5092 5093| ID| **Error Message** | 5094| ------------ | -------------------------------------- | 5095| 15100003 | Database corrupted. | 5096| 15100004 | Not found. | 5097| 15100005 | Database or result set already closed. | 5098 5099**Example** 5100 5101```js 5102let kvStore; 5103const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 5104const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; 5105try { 5106 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async () => { 5107 console.info('Succeeded in putting'); 5108 kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { 5109 console.info('Succeeded in getting'); 5110 }).catch((err) => { 5111 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 5112 }); 5113 }).catch((error) => { 5114 console.error(`Failed to put.code is ${error.code},message is ${error.message}`); 5115 }); 5116} catch (e) { 5117 console.error(`Failed to get.code is ${e.code},message is ${e.message}`); 5118} 5119``` 5120 5121### getEntries 5122 5123getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void 5124 5125Obtains all KV pairs that match the specified key prefix for this device. This API uses an asynchronous callback to return the result. 5126 5127**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5128 5129**Parameters** 5130 5131| Name | Type | Mandatory| Description | 5132| --------- | -------------------------------------- | ---- | ---------------------------------------- | 5133| keyPrefix | string | Yes | Key prefix to match. | 5134| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs that match the specified prefix.| 5135 5136**Error codes** 5137 5138For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5139 5140| ID| **Error Message** | 5141| ------------ | -------------------------------------- | 5142| 15100003 | Database corrupted. | 5143| 15100005 | Database or result set already closed. | 5144 5145**Example** 5146 5147```js 5148let kvStore; 5149try { 5150 let entries = []; 5151 for (var i = 0; i < 10; i++) { 5152 var key = 'batch_test_string_key'; 5153 var entry = { 5154 key: key + i, 5155 value: { 5156 type: distributedKVStore.ValueType.STRING, 5157 value: 'batch_test_string_value' 5158 } 5159 } 5160 entries.push(entry); 5161 } 5162 console.info(`entries: ${entries}`); 5163 kvStore.putBatch(entries, async function (err) { 5164 if (err != undefined) { 5165 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 5166 return; 5167 } 5168 console.info('Succeeded in putting Batch'); 5169 kvStore.getEntries('batch_test_string_key', function (err, entries) { 5170 if (err != undefined) { 5171 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 5172 return; 5173 } 5174 console.info('Succeeded in getting Entries'); 5175 console.info(`entries.length: ${entries.length}`); 5176 console.info(`entries[0]: ${entries[0]}`); 5177 }); 5178 }); 5179} catch (e) { 5180 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); 5181} 5182``` 5183 5184### getEntries 5185 5186getEntries(keyPrefix: string): Promise<Entry[]> 5187 5188Obtains all KV pairs that match the specified key prefix for this device. This API uses a promise to return the result. 5189 5190**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5191 5192**Parameters** 5193 5194| Name | Type | Mandatory| Description | 5195| --------- | ------ | ---- | -------------------- | 5196| keyPrefix | string | Yes | Key prefix to match.| 5197 5198**Return value** 5199 5200| Type | Description | 5201| -------------------------------- | ------------------------------------------- | 5202| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified prefix.| 5203 5204**Error codes** 5205 5206For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5207 5208| ID| **Error Message** | 5209| ------------ | -------------------------------------- | 5210| 15100003 | Database corrupted. | 5211| 15100005 | Database or result set already closed. | 5212 5213**Example** 5214 5215```js 5216let kvStore; 5217try { 5218 let entries = []; 5219 for (var i = 0; i < 10; i++) { 5220 var key = 'batch_test_string_key'; 5221 var entry = { 5222 key: key + i, 5223 value: { 5224 type: distributedKVStore.ValueType.STRING, 5225 value: 'batch_test_string_value' 5226 } 5227 } 5228 entries.push(entry); 5229 } 5230 console.info(`entries: ${entries}`); 5231 kvStore.putBatch(entries).then(async () => { 5232 console.info('Succeeded in putting Batch'); 5233 kvStore.getEntries('batch_test_string_key').then((entries) => { 5234 console.info('Succeeded in getting Entries'); 5235 console.info(`PutBatch ${entries}`); 5236 }).catch((err) => { 5237 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 5238 }); 5239 }).catch((err) => { 5240 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 5241 }); 5242} catch (e) { 5243 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); 5244} 5245``` 5246 5247### getEntries 5248 5249getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void 5250 5251Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. 5252 5253**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5254 5255**Parameters** 5256 5257| Name | Type | Mandatory| Description | 5258| --------- | -------------------------------------- | ---- | ---------------------------------------------- | 5259| deviceId | string | Yes | ID of the target device. | 5260| keyPrefix | string | Yes | Key prefix to match. | 5261| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| 5262 5263**Error codes** 5264 5265For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5266 5267| ID| **Error Message** | 5268| ------------ | -------------------------------------- | 5269| 15100003 | Database corrupted. | 5270| 15100005 | Database or result set already closed. | 5271 5272**Example** 5273 5274```js 5275let kvStore; 5276try { 5277 let entries = []; 5278 for (var i = 0; i < 10; i++) { 5279 var key = 'batch_test_string_key'; 5280 var entry = { 5281 key: key + i, 5282 value: { 5283 type: distributedKVStore.ValueType.STRING, 5284 value: 'batch_test_string_value' 5285 } 5286 } 5287 entries.push(entry); 5288 } 5289 console.info(`entries : ${entries}`); 5290 kvStore.putBatch(entries, async function (err) { 5291 if (err != undefined) { 5292 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 5293 return; 5294 } 5295 console.info('Succeeded in putting batch'); 5296 kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err, entries) { 5297 if (err != undefined) { 5298 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 5299 return; 5300 } 5301 console.info('Succeeded in getting entries'); 5302 console.info(`entries.length: ${entries.length}`); 5303 console.info(`entries[0]: ${entries[0]}`); 5304 }); 5305 }); 5306} catch (e) { 5307 console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`); 5308} 5309``` 5310 5311### getEntries 5312 5313getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> 5314 5315Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. 5316 5317**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5318 5319**Parameters** 5320 5321| Name | Type| Mandatory| Description | 5322| --------- | -------- | ---- | ------------------------ | 5323| deviceId | string | Yes | ID of the target device.| 5324| keyPrefix | string | Yes | Key prefix to match. | 5325 5326**Return value** 5327 5328| Type | Description | 5329| -------------------------------- | ------------------------------------------------- | 5330| Promise<[Entry](#entry)[]> | Promise used to return all the KV pairs that match the given condition.| 5331 5332**Error codes** 5333 5334For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5335 5336| ID| **Error Message** | 5337| ------------ | -------------------------------------- | 5338| 15100003 | Database corrupted. | 5339| 15100005 | Database or result set already closed. | 5340 5341**Example** 5342 5343```js 5344let kvStore; 5345try { 5346 let entries = []; 5347 for (var i = 0; i < 10; i++) { 5348 var key = 'batch_test_string_key'; 5349 var entry = { 5350 key: key + i, 5351 value: { 5352 type: distributedKVStore.ValueType.STRING, 5353 value: 'batch_test_string_value' 5354 } 5355 } 5356 entries.push(entry); 5357 } 5358 console.info(`entries: ${entries}`); 5359 kvStore.putBatch(entries).then(async () => { 5360 console.info('Succeeded in putting batch'); 5361 kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { 5362 console.info('Succeeded in getting entries'); 5363 console.info(`entries.length: ${entries.length}`); 5364 console.info(`entries[0]: ${entries[0]}`); 5365 console.info(`entries[0].value: ${entries[0].value}`); 5366 console.info(`entries[0].value.value: ${entries[0].value.value}`); 5367 }).catch((err) => { 5368 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 5369 }); 5370 }).catch((err) => { 5371 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 5372 }); 5373} catch (e) { 5374 console.error(`Failed to put batch.code is ${e.code},message is ${e.message}`); 5375} 5376``` 5377 5378### getEntries 5379 5380getEntries(query: Query, callback: AsyncCallback<Entry[]>): void 5381 5382Obtains all KV pairs that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. 5383 5384**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5385 5386**Parameters** 5387 5388| Name | Type | Mandatory| Description | 5389| -------- | -------------------------------------- | ---- | ----------------------------------------------------- | 5390| query | [Query](#query) | Yes | Key prefix to match. | 5391| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs that match the specified **Query** object on the local device.| 5392 5393**Error codes** 5394 5395For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5396 5397| ID| **Error Message** | 5398| ------------ | -------------------------------------- | 5399| 15100003 | Database corrupted. | 5400| 15100005 | Database or result set already closed. | 5401 5402**Example** 5403 5404```js 5405let kvStore; 5406try { 5407 var arr = new Uint8Array([21, 31]); 5408 let entries = []; 5409 for (var i = 0; i < 10; i++) { 5410 var key = 'batch_test_bool_key'; 5411 var entry = { 5412 key: key + i, 5413 value: { 5414 type: distributedKVStore.ValueType.BYTE_ARRAY, 5415 value: arr 5416 } 5417 } 5418 entries.push(entry); 5419 } 5420 console.info(`entries: {entries}`); 5421 kvStore.putBatch(entries, async function (err) { 5422 console.info('Succeeded in putting Batch'); 5423 const query = new distributedKVStore.Query(); 5424 query.prefixKey("batch_test"); 5425 kvStore.getEntries(query, function (err, entries) { 5426 if (err != undefined) { 5427 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 5428 return; 5429 } 5430 console.info('Succeeded in getting Entries'); 5431 console.info(`entries.length: ${entries.length}`); 5432 console.info(`entries[0]: ${entries[0]}`); 5433 }); 5434 }); 5435} catch (e) { 5436 console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`); 5437} 5438``` 5439 5440### getEntries 5441 5442getEntries(query: Query): Promise<Entry[]> 5443 5444Obtains all KV pairs that match the specified **Query** object for this device. This API uses a promise to return the result. 5445 5446**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5447 5448**Parameters** 5449 5450| Name| Type | Mandatory| Description | 5451| ------ | -------------- | ---- | -------------- | 5452| query | [Query](#query) | Yes | **Query** object to match.| 5453 5454**Return value** 5455 5456| Type | Description | 5457| -------------------------------- | -------------------------------------------------------- | 5458| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified **Query** object on the local device.| 5459 5460**Error codes** 5461 5462For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5463 5464| ID| **Error Message** | 5465| ------------ | -------------------------------------- | 5466| 15100003 | Database corrupted. | 5467| 15100005 | Database or result set already closed. | 5468 5469**Example** 5470 5471```js 5472let kvStore; 5473try { 5474 var arr = new Uint8Array([21, 31]); 5475 let entries = []; 5476 for (var i = 0; i < 10; i++) { 5477 var key = 'batch_test_bool_key'; 5478 var entry = { 5479 key: key + i, 5480 value: { 5481 type: distributedKVStore.ValueType.BYTE_ARRAY, 5482 value: arr 5483 } 5484 } 5485 entries.push(entry); 5486 } 5487 console.info(`entries: {entries}`); 5488 kvStore.putBatch(entries).then(async () => { 5489 console.info('Succeeded in putting Batch'); 5490 const query = new distributedKVStore.Query(); 5491 query.prefixKey("batch_test"); 5492 kvStore.getEntries(query).then((entries) => { 5493 console.info('Succeeded in getting Entries'); 5494 }).catch((err) => { 5495 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 5496 }); 5497 }).catch((err) => { 5498 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`) 5499 }); 5500 console.info('Succeeded in getting Entries'); 5501} catch (e) { 5502 console.error(`Failed to get Entries.code is ${e.code},message is ${e.message}`); 5503} 5504``` 5505 5506### getEntries 5507 5508getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void 5509 5510Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 5511 5512**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5513 5514**Parameters** 5515 5516| Name | Type | Mandatory| Description | 5517| -------- | -------------------------------------- | ---- | ------------------------------------------------------- | 5518| deviceId | string | Yes | ID of the target device. | 5519| query | [Query](#query) | Yes | **Query** object to match. | 5520| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs that match the specified device ID and **Query** object.| 5521 5522**Error codes** 5523 5524For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5525 5526| ID| **Error Message** | 5527| ------------ | -------------------------------------- | 5528| 15100003 | Database corrupted. | 5529| 15100005 | Database or result set already closed. | 5530 5531**Example** 5532 5533```js 5534let kvStore; 5535try { 5536 var arr = new Uint8Array([21, 31]); 5537 let entries = []; 5538 for (var i = 0; i < 10; i++) { 5539 var key = 'batch_test_bool_key'; 5540 var entry = { 5541 key: key + i, 5542 value: { 5543 type: distributedKVStore.ValueType.BYTE_ARRAY, 5544 value: arr 5545 } 5546 } 5547 entries.push(entry); 5548 } 5549 console.info(`entries: ${entries}`); 5550 kvStore.putBatch(entries, async function (err) { 5551 if (err != undefined) { 5552 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 5553 return; 5554 } 5555 console.info('Succeeded in putting batch'); 5556 var query = new distributedKVStore.Query(); 5557 query.deviceId('localDeviceId'); 5558 query.prefixKey("batch_test"); 5559 kvStore.getEntries('localDeviceId', query, function (err, entries) { 5560 if (err != undefined) { 5561 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 5562 return; 5563 } 5564 console.info('Succeeded in getting entries'); 5565 console.info(`entries.length: ${entries.length}`); 5566 console.info(`entries[0]: ${entries[0]}`); 5567 }) 5568 }); 5569 console.info('Succeeded in getting entries'); 5570} catch (e) { 5571 console.error(`Failed to get entries.code is ${e.code},message is ${e.message}`); 5572} 5573``` 5574 5575### getEntries 5576 5577getEntries(deviceId: string, query: Query): Promise<Entry[]> 5578 5579Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. 5580 5581**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5582 5583**Parameters** 5584 5585| Name | Type | Mandatory| Description | 5586| -------- | -------------- | ---- | -------------------- | 5587| deviceId | string | Yes | ID of the target device.| 5588| query | [Query](#query) | Yes | **Query** object to match. | 5589 5590**Return value** 5591 5592| Type | Description | 5593| -------------------------------- | ---------------------------------------------------------- | 5594| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified device ID and **Query** object.| 5595 5596**Error codes** 5597 5598For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5599 5600| ID| **Error Message** | 5601| ------------ | -------------------------------------- | 5602| 15100003 | Database corrupted. | 5603| 15100005 | Database or result set already closed. | 5604 5605**Example** 5606 5607```js 5608let kvStore; 5609try { 5610 var arr = new Uint8Array([21, 31]); 5611 let entries = []; 5612 for (var i = 0; i < 10; i++) { 5613 var key = 'batch_test_bool_key'; 5614 var entry = { 5615 key: key + i, 5616 value: { 5617 type: distributedKVStore.ValueType.BYTE_ARRAY, 5618 value: arr 5619 } 5620 } 5621 entries.push(entry); 5622 } 5623 console.info(`entries: ${entries}`); 5624 kvStore.putBatch(entries).then(async () => { 5625 console.info('Succeeded in putting batch'); 5626 var query = new distributedKVStore.Query(); 5627 query.deviceId('localDeviceId'); 5628 query.prefixKey("batch_test"); 5629 kvStore.getEntries('localDeviceId', query).then((entries) => { 5630 console.info('Succeeded in getting entries'); 5631 }).catch((err) => { 5632 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 5633 }); 5634 }).catch((err) => { 5635 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 5636 }); 5637 console.info('Succeeded in getting entries'); 5638} catch (e) { 5639 console.error(`Failed to get entries.code is ${e.code},message is ${e.message}`); 5640} 5641``` 5642 5643### getResultSet 5644 5645getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void 5646 5647Obtains a result set with the specified prefix for this device. This API uses an asynchronous callback to return the result. 5648 5649**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5650 5651**Parameters** 5652 5653| Name | Type | Mandatory| Description | 5654| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | 5655| keyPrefix | string | Yes | Key prefix to match. | 5656| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the result set with the specified prefix.| 5657 5658**Error codes** 5659 5660For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5661 5662| ID| **Error Message** | 5663| ------------ | -------------------------------------- | 5664| 15100003 | Database corrupted. | 5665| 15100005 | Database or result set already closed. | 5666 5667**Example** 5668 5669```js 5670let kvStore; 5671try { 5672 let resultSet; 5673 let entries = []; 5674 for (var i = 0; i < 10; i++) { 5675 var key = 'batch_test_string_key'; 5676 var entry = { 5677 key: key + i, 5678 value: { 5679 type: distributedKVStore.ValueType.STRING, 5680 value: 'batch_test_string_value' 5681 } 5682 } 5683 entries.push(entry); 5684 } 5685 kvStore.putBatch(entries, async function (err) { 5686 if (err != undefined) { 5687 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 5688 return; 5689 } 5690 console.info('Succeeded in putting batch'); 5691 kvStore.getResultSet('batch_test_string_key', async function (err, result) { 5692 if (err != undefined) { 5693 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 5694 return; 5695 } 5696 console.info('Succeeded in getting result set'); 5697 resultSet = result; 5698 kvStore.closeResultSet(resultSet, function (err) { 5699 if (err != undefined) { 5700 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 5701 return; 5702 } 5703 console.info('Succeeded in closing result set'); 5704 }) 5705 }); 5706 }); 5707} catch (e) { 5708 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); 5709} 5710``` 5711 5712### getResultSet 5713 5714getResultSet(keyPrefix: string): Promise<KVStoreResultSet> 5715 5716Obtains a result set with the specified prefix for this device. This API uses a promise to return the result. 5717 5718**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5719 5720**Parameters** 5721 5722| Name | Type | Mandatory| Description | 5723| --------- | ------ | ---- | -------------------- | 5724| keyPrefix | string | Yes | Key prefix to match.| 5725 5726**Return value** 5727 5728| Type | Description | 5729| ---------------------------------------------------- | --------------------------------------- | 5730| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the result set with the specified prefix.| 5731 5732**Error codes** 5733 5734For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5735 5736| ID| **Error Message** | 5737| ------------ | -------------------------------------- | 5738| 15100003 | Database corrupted. | 5739| 15100005 | Database or result set already closed. | 5740 5741**Example** 5742 5743```js 5744let kvStore; 5745try { 5746 let resultSet; 5747 let entries = []; 5748 for (var i = 0; i < 10; i++) { 5749 var key = 'batch_test_string_key'; 5750 var entry = { 5751 key: key + i, 5752 value: { 5753 type: distributedKVStore.ValueType.STRING, 5754 value: 'batch_test_string_value' 5755 } 5756 } 5757 entries.push(entry); 5758 } 5759 kvStore.putBatch(entries).then(async () => { 5760 console.info('Succeeded in putting batch'); 5761 }).catch((err) => { 5762 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 5763 }); 5764 kvStore.getResultSet('batch_test_string_key').then((result) => { 5765 console.info('Succeeded in getting result set'); 5766 resultSet = result; 5767 }).catch((err) => { 5768 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 5769 }); 5770 kvStore.closeResultSet(resultSet).then(() => { 5771 console.info('Succeeded in closing result set'); 5772 }).catch((err) => { 5773 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 5774 }); 5775} catch (e) { 5776 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 5777} 5778``` 5779 5780### getResultSet 5781 5782getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void 5783 5784Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. 5785 5786**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5787 5788**Parameters** 5789 5790| Name | Type | Mandatory| Description | 5791| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 5792| deviceId | string | Yes | ID of the target device. | 5793| keyPrefix | string | Yes | Key prefix to match. | 5794| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object that matches the specified device ID and key prefix.| 5795 5796**Error codes** 5797 5798For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5799 5800| ID| **Error Message** | 5801| ------------ | -------------------------------------- | 5802| 15100003 | Database corrupted. | 5803| 15100005 | Database or result set already closed. | 5804 5805**Example** 5806 5807```js 5808let kvStore; 5809try { 5810 let resultSet; 5811 kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { 5812 if (err != undefined) { 5813 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 5814 return; 5815 } 5816 console.info('Succeeded in getting resultSet'); 5817 resultSet = result; 5818 kvStore.closeResultSet(resultSet, function (err) { 5819 if (err != undefined) { 5820 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 5821 return; 5822 } 5823 console.info('Succeeded in closing resultSet'); 5824 }) 5825 }); 5826} catch (e) { 5827 console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`); 5828} 5829``` 5830 5831### getResultSet 5832 5833getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet> 5834 5835Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. 5836 5837**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5838 5839**Parameters** 5840 5841| Name | Type| Mandatory| Description | 5842| --------- | -------- | ---- | ------------------------ | 5843| deviceId | string | Yes | ID of the target device.| 5844| keyPrefix | string | Yes | Key prefix to match. | 5845 5846**Return value** 5847 5848| Type | Description | 5849| ------------------------------------------------------ | ------------------------------------------------------------ | 5850| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object that matches the specified device ID and key prefix.| 5851 5852**Error codes** 5853 5854For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5855 5856| ID| **Error Message** | 5857| ------------ | -------------------------------------- | 5858| 15100003 | Database corrupted. | 5859| 15100005 | Database or result set already closed. | 5860 5861**Example** 5862 5863```js 5864let kvStore; 5865try { 5866 let resultSet; 5867 kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { 5868 console.info('Succeeded in getting resultSet'); 5869 resultSet = result; 5870 }).catch((err) => { 5871 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 5872 }); 5873 kvStore.closeResultSet(resultSet).then(() => { 5874 console.info('Succeeded in closing resultSet'); 5875 }).catch((err) => { 5876 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 5877 }); 5878} catch (e) { 5879 console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`); 5880} 5881``` 5882 5883### getResultSet 5884 5885getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreResultSet>): void 5886 5887Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 5888 5889**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5890 5891**Parameters** 5892 5893| Name | Type | Mandatory| Description | 5894| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 5895| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | 5896| query | [Query](#query) | Yes | **Query** object to match. | 5897| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object that matches the specified device ID and **Query** object.| 5898 5899**Error codes** 5900 5901For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5902 5903| ID| **Error Message** | 5904| ------------ | -------------------------------------- | 5905| 15100003 | Database corrupted. | 5906| 15100005 | Database or result set already closed. | 5907 5908**Example** 5909 5910```js 5911let kvStore; 5912try { 5913 let resultSet; 5914 let entries = []; 5915 for (var i = 0; i < 10; i++) { 5916 var key = 'batch_test_string_key'; 5917 var entry = { 5918 key: key + i, 5919 value: { 5920 type: distributedKVStore.ValueType.STRING, 5921 value: 'batch_test_string_value' 5922 } 5923 } 5924 entries.push(entry); 5925 } 5926 kvStore.putBatch(entries, async function (err) { 5927 if (err != undefined) { 5928 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 5929 return; 5930 } 5931 console.info('Succeeded in putting batch'); 5932 const query = new distributedKVStore.Query(); 5933 query.prefixKey("batch_test"); 5934 kvStore.getResultSet('localDeviceId', query, async function (err, result) { 5935 if (err != undefined) { 5936 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 5937 return; 5938 } 5939 console.info('Succeeded in getting resultSet'); 5940 resultSet = result; 5941 kvStore.closeResultSet(resultSet, function (err) { 5942 if (err != undefined) { 5943 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 5944 return; 5945 } 5946 console.info('Succeeded in closing resultSet'); 5947 }) 5948 }); 5949 }); 5950} catch (e) { 5951 console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`); 5952} 5953``` 5954 5955### getResultSet 5956 5957getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> 5958 5959Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. 5960 5961**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5962 5963**Parameters** 5964 5965| Name | Type | Mandatory| Description | 5966| -------- | -------------- | ---- | ---------------------------------- | 5967| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| 5968| query | [Query](#query) | Yes | **Query** object to match. | 5969 5970**Return value** 5971 5972| Type | Description | 5973| ------------------------------------------------------ | ------------------------------------------------------------ | 5974| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object that matches the specified device ID and **Query** object.| 5975 5976**Error codes** 5977 5978For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5979 5980| ID| **Error Message** | 5981| ------------ | -------------------------------------- | 5982| 15100003 | Database corrupted. | 5983| 15100005 | Database or result set already closed. | 5984 5985**Example** 5986 5987```js 5988let kvStore; 5989try { 5990 let resultSet; 5991 let entries = []; 5992 for (var i = 0; i < 10; i++) { 5993 var key = 'batch_test_string_key'; 5994 var entry = { 5995 key: key + i, 5996 value: { 5997 type: distributedKVStore.ValueType.STRING, 5998 value: 'batch_test_string_value' 5999 } 6000 } 6001 entries.push(entry); 6002 } 6003 kvStore.putBatch(entries).then(async () => { 6004 console.info('Succeeded in putting batch'); 6005 }).catch((err) => { 6006 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6007 }); 6008 const query = new distributedKVStore.Query(); 6009 query.prefixKey("batch_test"); 6010 kvStore.getResultSet('localDeviceId', query).then((result) => { 6011 console.info('Succeeded in getting resultSet'); 6012 resultSet = result; 6013 }).catch((err) => { 6014 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6015 }); 6016 query.deviceId('localDeviceId'); 6017 console.info("GetResultSet " + query.getSqlLike()); 6018 kvStore.closeResultSet(resultSet).then(() => { 6019 console.info('Succeeded in closing resultSet'); 6020 }).catch((err) => { 6021 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6022 }); 6023 6024} catch (e) { 6025 console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`); 6026} 6027``` 6028 6029### getResultSet 6030 6031getResultSet(query: Query): Promise<KVStoreResultSet> 6032 6033Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses a promise to return the result. 6034 6035**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6036 6037**Parameters** 6038 6039| Name| Type | Mandatory| Description | 6040| ------ | -------------- | ---- | -------------- | 6041| query | [Query](#query) | Yes | **Query** object to match.| 6042 6043**Return value** 6044 6045| Type | Description | 6046| ---------------------------------------------------- | ------------------------------------------------------------ | 6047| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| 6048 6049**Error codes** 6050 6051For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6052 6053| ID| **Error Message** | 6054| ------------ | -------------------------------------- | 6055| 15100003 | Database corrupted. | 6056| 15100005 | Database or result set already closed. | 6057 6058**Example** 6059 6060```js 6061let kvStore; 6062try { 6063 let resultSet; 6064 let entries = []; 6065 for (var i = 0; i < 10; i++) { 6066 var key = 'batch_test_string_key'; 6067 var entry = { 6068 key: key + i, 6069 value: { 6070 type: distributedKVStore.ValueType.STRING, 6071 value: 'batch_test_string_value' 6072 } 6073 } 6074 entries.push(entry); 6075 } 6076 kvStore.putBatch(entries).then(async () => { 6077 console.info('Succeeded in putting batch'); 6078 }).catch((err) => { 6079 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6080 }); 6081 const query = new distributedKVStore.Query(); 6082 query.prefixKey("batch_test"); 6083 kvStore.getResultSet(query).then((result) => { 6084 console.info('Succeeded in getting result set'); 6085 resultSet = result; 6086 }).catch((err) => { 6087 console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); 6088 }); 6089} catch (e) { 6090 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 6091} 6092``` 6093 6094### getResultSet 6095 6096getResultSet(query: Query, callback:AsyncCallback<KVStoreResultSet>): void 6097 6098Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. 6099 6100**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6101 6102**Parameters** 6103 6104| Name | Type | Mandatory| Description | 6105| -------- | -------------- | ---- | ---------------------------------- | 6106| query | [Query](#query) | Yes | **Query** object to match. | 6107| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained. | 6108 6109**Error codes** 6110 6111For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6112 6113| ID| **Error Message** | 6114| ------------ | -------------------------------------- | 6115| 15100003 | Database corrupted. | 6116| 15100005 | Database or result set already closed. | 6117 6118**Example** 6119 6120```js 6121let kvStore; 6122try { 6123 let resultSet; 6124 let entries = []; 6125 for (var i = 0; i < 10; i++) { 6126 var key = 'batch_test_string_key'; 6127 var entry = { 6128 key: key + i, 6129 value: { 6130 type: distributedKVStore.ValueType.STRING, 6131 value: 'batch_test_string_value' 6132 } 6133 } 6134 entries.push(entry); 6135 } 6136 kvStore.putBatch(entries, async function (err) { 6137 if (err != undefined) { 6138 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6139 return; 6140 } 6141 console.info('Succeeded in putting batch'); 6142 const query = new distributedKVStore.Query(); 6143 query.prefixKey("batch_test"); 6144 kvStore.getResultSet(query, async function (err, result) { 6145 if (err != undefined) { 6146 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6147 return; 6148 } 6149 console.info('Succeeded in getting resultSet'); 6150 resultSet = result; 6151 kvStore.closeResultSet(resultSet, function (err) { 6152 if (err != undefined) { 6153 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6154 return; 6155 } 6156 console.info('Succeeded in closing resultSet'); 6157 }) 6158 }); 6159 }); 6160} catch (e) { 6161 console.error(`Failed to get resultSet.code is ${e.code},message is ${e.message}`); 6162} 6163``` 6164 6165### getResultSet 6166 6167getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void 6168 6169Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses an asynchronous callback to return the result. 6170 6171**System API**: This is a system API. 6172 6173**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 6174 6175**Parameters** 6176 6177| Name | Type | Mandatory| Description | 6178| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 6179| 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. | 6180| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| 6181 6182**Error codes** 6183 6184For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6185 6186| ID| **Error Message** | 6187| ------------ | -------------------------------------- | 6188| 15100003 | Database corrupted. | 6189| 15100005 | Database or result set already closed. | 6190 6191**Example** 6192 6193```js 6194import dataSharePredicates from '@ohos.data.dataSharePredicates'; 6195 6196let kvStore; 6197try { 6198 let resultSet; 6199 let predicates = new dataSharePredicates.DataSharePredicates(); 6200 predicates.prefixKey("batch_test_string_key"); 6201 kvStore.getResultSet(predicates, async function (err, result) { 6202 if (err != undefined) { 6203 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6204 return; 6205 } 6206 console.info('Succeeded in getting result set'); 6207 resultSet = result; 6208 kvStore.closeResultSet(resultSet, function (err) { 6209 if (err != undefined) { 6210 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 6211 return; 6212 } 6213 console.info('Succeeded in closing result set'); 6214 }) 6215 }); 6216} catch (e) { 6217 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 6218} 6219``` 6220 6221### getResultSet 6222 6223getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> 6224 6225Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses a promise to return the result. 6226 6227**System API**: This is a system API. 6228 6229**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 6230 6231**Parameters** 6232 6233| Name | Type | Mandatory| Description | 6234| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | 6235| 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.| 6236 6237**Return value** 6238 6239| Type | Description | 6240| ---------------------------------------------------- | ------------------------- | 6241| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| 6242 6243**Error codes** 6244 6245For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6246 6247| ID| **Error Message** | 6248| ------------ | -------------------------------------- | 6249| 15100003 | Database corrupted. | 6250| 15100005 | Database or result set already closed. | 6251 6252**Example** 6253 6254```js 6255import dataSharePredicates from '@ohos.data.dataSharePredicates'; 6256 6257let kvStore; 6258try { 6259 let resultSet; 6260 let predicates = new dataSharePredicates.DataSharePredicates(); 6261 predicates.prefixKey("batch_test_string_key"); 6262 kvStore.getResultSet(predicates).then((result) => { 6263 console.info('Succeeded in getting result set'); 6264 resultSet = result; 6265 }).catch((err) => { 6266 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6267 }); 6268 kvStore.closeResultSet(resultSet).then(() => { 6269 console.info('Succeeded in closing result set'); 6270 }).catch((err) => { 6271 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 6272 }); 6273} catch (e) { 6274 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 6275} 6276``` 6277 6278### getResultSet 6279 6280getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void 6281 6282Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result. 6283 6284**System API**: This is a system API. 6285 6286**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 6287 6288**Parameters** 6289 6290| Name | Type | Mandatory| Description | 6291| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 6292| deviceId | string | Yes | ID of the target device. | 6293| 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. | 6294| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| 6295 6296**Error codes** 6297 6298For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6299 6300| ID| **Error Message** | 6301| ------------ | -------------------------------------- | 6302| 15100003 | Database corrupted. | 6303| 15100005 | Database or result set already closed. | 6304 6305**Example** 6306 6307```js 6308import dataSharePredicates from '@ohos.data.dataSharePredicates'; 6309 6310let kvStore; 6311try { 6312 let resultSet; 6313 let predicates = new dataSharePredicates.DataSharePredicates(); 6314 predicates.prefixKey("batch_test_string_key"); 6315 kvStore.getResultSet('localDeviceId', predicates, async function (err, result) { 6316 if (err != undefined) { 6317 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6318 return; 6319 } 6320 console.info('Succeeded in getting result set'); 6321 resultSet = result; 6322 kvStore.closeResultSet(resultSet, function (err) { 6323 if (err != undefined) { 6324 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 6325 return; 6326 } 6327 console.info('Succeeded in closing result set'); 6328 }) 6329 }); 6330} catch (e) { 6331 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 6332} 6333``` 6334 6335### getResultSet 6336 6337getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> 6338 6339Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result. 6340 6341**System API**: This is a system API. 6342 6343**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 6344 6345**Parameters** 6346 6347| Name | Type | Mandatory| Description | 6348| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | 6349| deviceId | string | Yes | ID of the target device. | 6350| 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.| 6351 6352**Return value** 6353 6354| Type | Description | 6355| ---------------------------------------------------- | ------------------------- | 6356| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| 6357 6358**Error codes** 6359 6360For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6361 6362| ID| **Error Message** | 6363| ------------ | -------------------------------------- | 6364| 15100003 | Database corrupted. | 6365| 15100005 | Database or result set already closed. | 6366 6367**Example** 6368 6369```js 6370import dataSharePredicates from '@ohos.data.dataSharePredicates'; 6371let kvStore; 6372try { 6373 let resultSet; 6374 let predicates = new dataSharePredicates.DataSharePredicates(); 6375 predicates.prefixKey("batch_test_string_key"); 6376 kvStore.getResultSet('localDeviceId', predicates).then((result) => { 6377 console.info('Succeeded in getting result set'); 6378 resultSet = result; 6379 }).catch((err) => { 6380 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6381 }); 6382 kvStore.closeResultSet(resultSet).then(() => { 6383 console.info('Succeeded in closing result set'); 6384 }).catch((err) => { 6385 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 6386 }); 6387} catch (e) { 6388 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 6389} 6390``` 6391 6392### getResultSize 6393 6394getResultSize(query: Query, callback: AsyncCallback<number>): void 6395 6396Obtains the number of results that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. 6397 6398**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6399 6400**Parameters** 6401 6402| Name | Type | Mandatory| Description | 6403| -------- | --------------------------- | ---- | ------------------------------------------------- | 6404| query | [Query](#query) | Yes | **Query** object to match. | 6405| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| 6406 6407**Error codes** 6408 6409For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6410 6411| ID| **Error Message** | 6412| ------------ | -------------------------------------- | 6413| 15100003 | Database corrupted. | 6414| 15100005 | Database or result set already closed. | 6415 6416**Example** 6417 6418```js 6419let kvStore; 6420try { 6421 let entries = []; 6422 for (var i = 0; i < 10; i++) { 6423 var key = 'batch_test_string_key'; 6424 var entry = { 6425 key: key + i, 6426 value: { 6427 type: distributedKVStore.ValueType.STRING, 6428 value: 'batch_test_string_value' 6429 } 6430 } 6431 entries.push(entry); 6432 } 6433 kvStore.putBatch(entries, async function (err) { 6434 console.info('Succeeded in putting batch'); 6435 const query = new distributedKVStore.Query(); 6436 query.prefixKey("batch_test"); 6437 kvStore.getResultSize(query, async function (err, resultSize) { 6438 if (err != undefined) { 6439 console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); 6440 return; 6441 } 6442 console.info('Succeeded in getting result set size'); 6443 }); 6444 }); 6445} catch (e) { 6446 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 6447} 6448``` 6449 6450### getResultSize 6451 6452getResultSize(query: Query): Promise<number> 6453 6454Obtains the number of results that match the specified **Query** object for this device. This API uses a promise to return the result. 6455 6456**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6457 6458**Parameters** 6459 6460| Name| Type | Mandatory| Description | 6461| ------ | -------------- | ---- | -------------- | 6462| query | [Query](#query) | Yes | **Query** object to match.| 6463 6464**Return value** 6465 6466| Type | Description | 6467| --------------------- | ---------------------------------------------------- | 6468| Promise<number> | Promise used to return the number of results obtained.| 6469 6470**Error codes** 6471 6472For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6473 6474| ID| **Error Message** | 6475| ------------ | -------------------------------------- | 6476| 15100003 | Database corrupted. | 6477| 15100005 | Database or result set already closed. | 6478 6479**Example** 6480 6481```js 6482let kvStore; 6483try { 6484 let entries = []; 6485 for (var i = 0; i < 10; i++) { 6486 var key = 'batch_test_string_key'; 6487 var entry = { 6488 key: key + i, 6489 value: { 6490 type: distributedKVStore.ValueType.STRING, 6491 value: 'batch_test_string_value' 6492 } 6493 } 6494 entries.push(entry); 6495 } 6496 kvStore.putBatch(entries).then(async () => { 6497 console.info('Succeeded in putting batch'); 6498 }).catch((err) => { 6499 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6500 }); 6501 const query = new distributedKVStore.Query(); 6502 query.prefixKey("batch_test"); 6503 kvStore.getResultSize(query).then((resultSize) => { 6504 console.info('Succeeded in getting result set size'); 6505 }).catch((err) => { 6506 console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); 6507 }); 6508} catch (e) { 6509 console.error(`An unexpected error occurred.code is ${e.code},message is ${e.code}`); 6510} 6511``` 6512 6513### getResultSize 6514 6515getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; 6516 6517Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 6518 6519**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6520 6521**Parameters** 6522 6523| Name | Type | Mandatory| Description | 6524| -------- | --------------------------- | ---- | --------------------------------------------------- | 6525| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | 6526| query | [Query](#query) | Yes | **Query** object to match. | 6527| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained. | 6528 6529**Error codes** 6530 6531For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6532 6533| ID| **Error Message** | 6534| ------------ | -------------------------------------- | 6535| 15100003 | Database corrupted. | 6536| 15100005 | Database or result set already closed. | 6537 6538**Example** 6539 6540```js 6541let kvStore; 6542try { 6543 let entries = []; 6544 for (var i = 0; i < 10; i++) { 6545 var key = 'batch_test_string_key'; 6546 var entry = { 6547 key: key + i, 6548 value: { 6549 type: distributedKVStore.ValueType.STRING, 6550 value: 'batch_test_string_value' 6551 } 6552 } 6553 entries.push(entry); 6554 } 6555 kvStore.putBatch(entries, async function (err) { 6556 if (err != undefined) { 6557 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6558 return; 6559 } 6560 console.info('Succeeded in putting batch'); 6561 const query = new distributedKVStore.Query(); 6562 query.prefixKey("batch_test"); 6563 kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { 6564 if (err != undefined) { 6565 console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`); 6566 return; 6567 } 6568 console.info('Succeeded in getting resultSize'); 6569 }); 6570 }); 6571} catch (e) { 6572 console.error(`Failed to get resultSize.code is ${e.code},message is ${e.message}`); 6573} 6574``` 6575 6576### getResultSize 6577 6578getResultSize(deviceId: string, query: Query): Promise<number> 6579 6580Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. 6581 6582**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6583 6584**Parameters** 6585 6586| Name | Type | Mandatory| Description | 6587| -------- | -------------- | ---- | ---------------------------------- | 6588| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| 6589| query | [Query](#query) | Yes | **Query** object to match. | 6590 6591**Return value** 6592 6593| Type | Description | 6594| --------------------- | ------------------------------------------------------ | 6595| Promise<number> | Promise used to return the number of results obtained. | 6596 6597**Error codes** 6598 6599For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6600 6601| ID| **Error Message** | 6602| ------------ | -------------------------------------- | 6603| 15100003 | Database corrupted. | 6604| 15100005 | Database or result set already closed. | 6605 6606**Example** 6607 6608```js 6609let kvStore; 6610try { 6611 let entries = []; 6612 for (var i = 0; i < 10; i++) { 6613 var key = 'batch_test_string_key'; 6614 var entry = { 6615 key: key + i, 6616 value: { 6617 type: distributedKVStore.ValueType.STRING, 6618 value: 'batch_test_string_value' 6619 } 6620 } 6621 entries.push(entry); 6622 } 6623 kvStore.putBatch(entries).then(async () => { 6624 console.info('Succeeded in putting batch'); 6625 }).catch((err) => { 6626 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6627 }); 6628 var query = new distributedKVStore.Query(); 6629 query.prefixKey("batch_test"); 6630 kvStore.getResultSize('localDeviceId', query).then((resultSize) => { 6631 console.info('Succeeded in getting resultSize'); 6632 }).catch((err) => { 6633 console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`); 6634 }); 6635} catch (e) { 6636 console.error(`Failed to get resultSize.code is ${e.code},message is ${e.message}`); 6637} 6638``` 6639