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