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