1 # @ohos.data.distributedKVStore (Distributed KV Store) 2 3The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. You can use the APIs provided by this module to save application data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores. 4 5The **distributedKVStore** module provides the following functions: 6 7- [KVManager](#kvmanager): provides a **KVManager** instance to obtain KV store information. 8- [KVStoreResultSet](#kvstoreresultset): provides APIs for accessing the results obtained from a KV store. 9- [Query](#query): provides APIs for setting predicates for data query. 10- [SingleKVStore](#singlekvstore): provides APIs for querying and synchronizing data in single KV stores. The single KV stores manage data without distinguishing devices. 11- [DeviceKVStore](#devicekvstore): provides APIs for querying and synchronizing data in device KV stores. This class inherits from [SingleKVStore](#singlekvstore). The device KV stores manage data by device. 12 13> **NOTE** 14> 15> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. 16 17## Modules to Import 18 19```ts 20import distributedKVStore from '@ohos.data.distributedKVStore'; 21``` 22 23## KVManagerConfig 24 25Provides the **KVManager** instance configuration, including the bundle name of the invoker and the application context. 26 27**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 28 29| Name | Type | Mandatory| Description | 30| ---------- | --------------------- | ---- | ------------------------------------------------------------ | 31| context | Context | Yes |Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).<br>Since API version 10, the type of **context** is [BaseContext](js-apis-inner-application-baseContext.md).| 32| bundleName | string | Yes | Bundle name. | 33 34## Constants 35 36Provides constants of the distributed KV store. 37 38**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 39 40| Name | Value | Description | 41| --------------------- | ------- | --------------------------------------- | 42| MAX_KEY_LENGTH | 1024 | Maximum length of a key in a distributed KV store, in bytes. | 43| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in a distributed KV store, in bytes.| 44| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a key in a device KV store, in bytes.| 45| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. | 46| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes. | 47| MAX_BATCH_SIZE | 128 | Maximum number of batch operations. | 48 49## ValueType 50 51Enumerates the types of the value in a KV pair. 52 53**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 54 55| Name | Description | 56| ---------- | ---------------------- | 57| STRING | String. | 58| INTEGER | Integer. | 59| FLOAT | Float (single-precision floating point). | 60| BYTE_ARRAY | Byte array.| 61| BOOLEAN | Boolean. | 62| DOUBLE | Double (double-precision floating point).| 63 64## Value 65 66Defines the **value** object in a KV store. 67 68**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 69 70| Name | Type |Mandatory | Description | 71| ----- | ------- |-----|------------------------ | 72| type | [ValueType](#valuetype) | Yes|Type of the value. | 73| value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair. | 74 75## Entry 76 77Defines the KV pairs stored in a KV store. 78 79**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 80 81| Name | Type | Mandatory| Description | 82| ----- | --------------- | ---- | -------- | 83| key | string | Yes | Key of a KV pair in the KV store. | 84| value | [Value](#value) | Yes | Value of a KV pair in the KV store. | 85 86## ChangeNotification 87 88Defines the content of a data change notification, including inserted data, updated data, deleted data, and device ID. 89 90**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 91 92| Name | Type | Mandatory | Description | 93| ------------- | ----------------- | ---- | ------------------------ | 94| insertEntries | [Entry](#entry)[] | Yes | Data inserted. | 95| updateEntries | [Entry](#entry)[] | Yes | Data updated. | 96| deleteEntries | [Entry](#entry)[] | Yes | Data deleted. | 97| deviceId | string | Yes | UUID of the device.| 98 99## SyncMode 100 101Enumerates the synchronization modes. 102 103**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 104 105| Name | Description | 106| --------- | ---------------------------------------------------- | 107| PULL_ONLY | Pull data from the peer end to the local end only. | 108| PUSH_ONLY | Push data from the local end to the peer end only. | 109| PUSH_PULL | Push data from the local end to the peer end and then pull data from the peer end to the local end.| 110 111## SubscribeType 112 113Enumerates the subscription types. 114 115**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 116 117| Name | Description | 118| --------------------- | ---------------------------- | 119| SUBSCRIBE_TYPE_LOCAL | Local data changes. | 120| SUBSCRIBE_TYPE_REMOTE | Remote data changes. | 121| SUBSCRIBE_TYPE_ALL | Local and remote data changes.| 122 123## KVStoreType 124 125Enumerates the distributed KV store types. 126 127| Name | Description | 128| -------------------- | ------------------------------------------------------------ | 129| DEVICE_COLLABORATION | Device KV store.<br>The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| 130| SINGLE_VERSION | Single KV store.<br>The single KV store does not differentiate data by device. If entries with the same key are modified on different devices, the value will be overwritten.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | 131 132## SecurityLevel 133 134Enumerates the KV store security levels. 135 136**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 137 138| Name | Description | 139| -------: | ------------------------------------------------------------ | 140| S1 | Low security level. Disclosure, tampering, corruption, or loss of the data may cause minor impact on an individual or group.<br>Examples: gender and nationality information, and user application records| 141| S2 | Medium security level. Disclosure, tampering, corruption, or loss of the data may cause major impact on an individual or group.<br>Examples: mailing addresses and nicknames of individuals| 142| S3 | High security level. Disclosure, tampering, corruption, or loss of the data may cause critical impact on an individual or group.<br>Examples: real-time precise positioning information and movement trajectory | 143| S4 | Critical security level. Disclosure, tampering, corruption, or loss of the data may cause significant adverse impact on an individual or group.<br>Examples: political opinions, religious and philosophical belief, trade union membership, genetic data, biological information, health and sexual life status, sexual orientation, device authentication, and personal credit card information| 144 145## Options 146 147Provides KV store configuration. 148 149| Name | Type | Mandatory| Description | 150| --------------- | -------------- | ---- | -------------------------| 151| createIfMissing | boolean | No | Whether to create a KV store if the database file does not exist. The default value is **true**, which means to create a KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 152| encrypt | boolean | No | Whether to encrypt the KV store. The default value is **false**, which means the KV store is not encrypted.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 153| backup | boolean | No | Whether to back up the KV store. The default value is **true**, which means to back up the KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 154| autoSync | boolean | No | Whether to automatically synchronize database files. The default value is **false**, which means the database files are manually synchronized.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core<br>**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC| 155| kvStoreType | [KVStoreType](#kvstoretype) | No | Type of the KV store to create. The default value is **DEVICE_COLLABORATION**, which indicates a device KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 156| securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the KV store.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| 157| schema | [Schema](#schema) | No | Schema used to define the values stored in the KV store. The default value is **undefined**, which means no schema is used.<br>**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| 158 159## Schema 160 161Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store. 162 163**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 164 165| Name | Type | Readable| Writable| Description | 166| ------- | ----------------------- | ---- | ---- | -------------------------- | 167| root | [FieldNode](#fieldnode) | Yes | Yes | JSON root object. | 168| indexes | Array\<string> | Yes | Yes | String array in JSON format.| 169| mode | number | Yes | Yes | Schema mode. | 170| skip | number | Yes | Yes | Size of a skip of the schema. | 171 172### constructor 173 174constructor() 175 176A constructor used to create a **Schema** instance. 177 178**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 179 180## FieldNode 181 182Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store. 183 184**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 185 186| Name | Type | Readable| Writable| Description | 187| -------- | ------- | ---- | ---- | ------------------------------ | 188| nullable | boolean | Yes | Yes | Whether the database field can be null. | 189| default | string | Yes | Yes | Default value of a **FieldNode**. | 190| type | number | Yes | Yes | Value of the data type corresponding to the specified node.| 191 192### constructor 193 194constructor(name: string) 195 196A constructor used to create a **FieldNode** instance with a string field. 197 198**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 199 200**Parameters** 201 202| Name| Type| Mandatory| Description | 203| ------ | -------- | ---- | --------------- | 204| name | string | Yes | Value of **FieldNode**.| 205 206### appendChild 207 208appendChild(child: FieldNode): boolean 209 210Appends a child node to this **FieldNode**. 211 212**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 213 214**Parameters** 215 216| Name| Type | Mandatory| Description | 217| ------ | ----------------------- | ---- | ---------------- | 218| child | [FieldNode](#fieldnode) | Yes | Child node to append.| 219 220**Return value** 221 222| Type | Description | 223| ------- | ------------------------------------------------------------ | 224| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 225 226**Example** 227 228```ts 229 230try { 231 let node: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("root"); 232 let child1: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("child1"); 233 let child2: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("child2"); 234 let child3: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("child3"); 235 node.appendChild(child1); 236 node.appendChild(child2); 237 node.appendChild(child3); 238 console.info("appendNode " + JSON.stringify(node)); 239 child1 = null; 240 child2 = null; 241 child3 = null; 242 node = null; 243} catch (e) { 244 console.error("AppendChild " + e); 245} 246``` 247 248## distributedKVStore.createKVManager 249 250createKVManager(config: KVManagerConfig): KVManager 251 252Creates a **KVManager** instance for KV store management. 253 254**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 255 256**Parameters** 257 258| Name| Type | Mandatory| Description | 259| ------ | ----------------------------- | ---- | --------------------------------------------------------- | 260| config | [KVManagerConfig](#kvmanagerconfig) | Yes | **KVManager** instance configuration, including the bundle name and user information of the caller.| 261 262**Return value** 263 264| Type | Description | 265| -------------------------------------- | ------------------------------------------ | 266| [KVManager](#kvmanager) | **KVManager** instance created.| 267 268**Example** 269 270Stage model: 271 272```ts 273import UIAbility from '@ohos.app.ability.UIAbility'; 274import { BusinessError } from '@ohos.base'; 275 276let kvManager: distributedKVStore.KVManager; 277 278export default class EntryAbility extends UIAbility { 279 onCreate() { 280 console.info("MyAbilityStage onCreate") 281 let context = this.context 282 const kvManagerConfig: distributedKVStore.KVManagerConfig = { 283 context: context, 284 bundleName: 'com.example.datamanagertest', 285 } 286 try { 287 kvManager = distributedKVStore.createKVManager(kvManagerConfig); 288 console.info("Succeeded in creating KVManager"); 289 } catch (e) { 290 let error = e as BusinessError; 291 console.error(`Failed to create KVManager.code is ${error.code},message is ${error.message}`); 292 } 293 } 294} 295``` 296 297FA model: 298 299```ts 300import featureAbility from '@ohos.ability.featureAbility'; 301import { BusinessError } from '@ohos.base'; 302 303let kvManager: distributedKVStore.KVManager; 304let context = featureAbility.getContext() 305const kvManagerConfig: distributedKVStore.KVManagerConfig = { 306 context: context, 307 bundleName: 'com.example.datamanagertest', 308} 309try { 310 kvManager = distributedKVStore.createKVManager(kvManagerConfig); 311 console.info("Succeeded in creating KVManager"); 312} catch (e) { 313 let error = e as BusinessError; 314 console.error(`Failed to create KVManager.code is ${error.code},message is ${error.message}`); 315} 316``` 317 318## KVManager 319 320Provides an instance to obtain information about a distributed KV store. Before calling any API in **KVManager**, you must use [createKVManager](#distributedkvstorecreatekvmanager) to create a **KVManager** instance. 321 322### getKVStore 323 324getKVStore<T>(storeId: string, options: Options, callback: AsyncCallback<T>): void 325 326Creates and obtains a distributed KV store. This API uses an asynchronous callback to return the result. 327 328**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 329 330**Parameters** 331 332| Name | Type | Mandatory| Description | 333| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 334| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| 335| options | [Options](#options) | Yes | Configuration of the KV store to create. | 336| callback | AsyncCallback<T> | Yes | Callback invoked to return the **SingleKVStore** or **DeviceKVStore** instance created.| 337 338**Error codes** 339 340For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 341 342| ID| **Error Message** | 343| ------------ | ------------------------------------------- | 344| 15100002 | Open existed database with changed options. | 345| 15100003 | Database corrupted. | 346 347**Example** 348 349```ts 350import { BusinessError } from '@ohos.base'; 351 352let 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 380Creates and obtains 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](../errorcodes/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](../errorcodes/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](../errorcodes/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 service status changes. If the service is terminated, you need to register the callbacks for data change notifications and synchronization complete notifications again. In addition, an error will be returned for a synchronization operation. 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 service status changes.| 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 service status changes. The **deathCallback** parameter must be a callback registered for subscribing to service status changes. 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 service status changes.| 793| deathCallback | Callback<void> | No | Callback for the service status changes. If this parameter is not specified, all subscriptions to the service status changes will be canceled. | 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](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 synchronization 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](../errorcodes/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](../errorcodes/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](../errorcodes/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](../errorcodes/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](../errorcodes/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](../errorcodes/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](../errorcodes/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](../errorcodes/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### putBatch 2490 2491 2492putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void 2493 2494Writes data to this single KV store. This API uses an asynchronous callback to return the result. 2495 2496**Model restriction**: This API can be used only in the stage model. 2497 2498**System API**: This is a system API. 2499 2500**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2501 2502**Parameters** 2503 2504| Name | Type | Mandatory| Description | 2505| -------- | ------------------------------------------------------------ | ---- | ------------------ | 2506| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write.| 2507| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 2508 2509**Error codes** 2510 2511For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2512 2513| ID| **Error Message** | 2514| ------------ | ---------------------------------------- | 2515| 15100003 | Database corrupted. | 2516| 15100005 | Database or result set already closed. | 2517 2518For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). 2519 2520| ID| **Error Message** | 2521| ------------ | -------------------------------------------- | 2522| 14800047 | The WAL file size exceeds the default limit. | 2523 2524**Example** 2525 2526```ts 2527import { BusinessError } from '@ohos.base'; 2528 2529try { 2530 let v8Arr: distributedKVStore.Entry[] = []; 2531 let arr = new Uint8Array([4, 5, 6, 7]); 2532 let vb1: distributedKVStore.Entry = { key: "name_1", value: 32 } 2533 let vb2: distributedKVStore.Entry = { key: "name_2", value: arr }; 2534 let vb3: distributedKVStore.Entry = { key: "name_3", value: "lisi" }; 2535 2536 v8Arr.push(vb1); 2537 v8Arr.push(vb2); 2538 v8Arr.push(vb3); 2539 kvStore.putBatch(v8Arr, async (err) => { 2540 if (err != undefined) { 2541 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 2542 return; 2543 } 2544 console.info('Succeeded in putting batch'); 2545 }) 2546} catch (e) { 2547 let error = e as BusinessError; 2548 console.error(`Failed to put batch.code is ${error.code},message is ${error.message}`); 2549} 2550``` 2551 2552### putBatch 2553 2554putBatch(value: Array<ValuesBucket>): Promise<void> 2555 2556Write data to this KV store. This API uses a promise to return the result. 2557 2558**Model restriction**: This API can be used only in the stage model. 2559 2560**System API**: This is a system API. 2561 2562**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2563 2564**Parameters** 2565 2566| Name| Type | Mandatory| Description | 2567| ------ | ------------------------------------------------------------ | ---- | ------------------ | 2568| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write. | 2569 2570**Return value** 2571 2572| Type | Description | 2573| ------------------- | ------------------------- | 2574| Promise<void> | Promise that returns no value.| 2575 2576**Error codes** 2577 2578For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2579 2580| ID| **Error Message** | 2581| ------------ | ---------------------------------------- | 2582| 15100003 | Database corrupted. | 2583| 15100005 | Database or result set already closed. | 2584 2585For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). 2586 2587| ID| **Error Message** | 2588| ------------ | -------------------------------------------- | 2589| 14800047 | The WAL file size exceeds the default limit. | 2590 2591**Example** 2592 2593```ts 2594import { BusinessError } from '@ohos.base'; 2595 2596try { 2597 let v8Arr: distributedKVStore.Entry[] = []; 2598 let arr = new Uint8Array([4, 5, 6, 7]); 2599 let vb1: distributedKVStore.Entry = { key: "name_1", value: 32 } 2600 let vb2: distributedKVStore.Entry = { key: "name_2", value: arr }; 2601 let vb3: distributedKVStore.Entry = { key: "name_3", value: "lisi" }; 2602 2603 v8Arr.push(vb1); 2604 v8Arr.push(vb2); 2605 v8Arr.push(vb3); 2606 kvStore.putBatch(v8Arr).then(async () => { 2607 console.info(`Succeeded in putting patch`); 2608 }).catch((err: BusinessError) => { 2609 console.error(`putBatch fail.code is ${err.code},message is ${err.message}`); 2610 }); 2611} catch (e) { 2612 let error = e as BusinessError; 2613 console.error(`putBatch fail.code is ${error.code},message is ${error.message}`); 2614} 2615``` 2616 2617### delete 2618 2619delete(key: string, callback: AsyncCallback<void>): void 2620 2621Deletes a KV pair from this KV store. This API uses an asynchronous callback to return the result. 2622 2623**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2624 2625**Parameters** 2626 2627| Name | Type | Mandatory| Description | 2628| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 2629| key | string | Yes | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 2630| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 2631 2632**Error codes** 2633 2634For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2635 2636| ID| **Error Message** | 2637| ------------ | -------------------------------------- | 2638| 15100003 | Database corrupted. | 2639| 15100005 | Database or result set already closed. | 2640 2641For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). 2642 2643| ID| **Error Message** | 2644| ------------ | -------------------------------------------- | 2645| 14800047 | The WAL file size exceeds the default limit. | 2646 2647**Example** 2648 2649```ts 2650import { BusinessError } from '@ohos.base'; 2651 2652const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2653const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2654try { 2655 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => { 2656 if (err != undefined) { 2657 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 2658 return; 2659 } 2660 console.info('Succeeded in putting'); 2661 if (kvStore != null) { 2662 kvStore.delete(KEY_TEST_STRING_ELEMENT, (err) => { 2663 if (err != undefined) { 2664 console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); 2665 return; 2666 } 2667 console.info('Succeeded in deleting'); 2668 }); 2669 } 2670 }); 2671} catch (e) { 2672 let error = e as BusinessError; 2673 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 2674} 2675``` 2676 2677### delete 2678 2679delete(key: string): Promise<void> 2680 2681Deletes a KV pair from this KV store. This API uses a promise to return the result. 2682 2683**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2684 2685**Parameters** 2686 2687| Name| Type| Mandatory| Description | 2688| ------ | -------- | ---- | ------------------------------------------------------------ | 2689| key | string | Yes | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 2690 2691**Return value** 2692 2693| Type | Description | 2694| ------------------- | ------------------------- | 2695| Promise<void> | Promise that returns no value.| 2696 2697**Error codes** 2698 2699For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2700 2701| ID| **Error Message** | 2702| ------------ | ---------------------------------------- | 2703| 15100003 | Database corrupted. | 2704| 15100005 | Database or result set already closed. | 2705 2706For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). 2707 2708| ID| **Error Message** | 2709| ------------ | -------------------------------------------- | 2710| 14800047 | The WAL file size exceeds the default limit. | 2711 2712**Example** 2713 2714```ts 2715import { BusinessError } from '@ohos.base'; 2716 2717const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 2718const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 2719try { 2720 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { 2721 console.info(`Succeeded in putting data`); 2722 if (kvStore != null) { 2723 kvStore.delete(KEY_TEST_STRING_ELEMENT).then(() => { 2724 console.info('Succeeded in deleting'); 2725 }).catch((err: BusinessError) => { 2726 console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); 2727 }); 2728 } 2729 }).catch((err: BusinessError) => { 2730 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 2731 }); 2732} catch (e) { 2733 let error = e as BusinessError; 2734 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 2735} 2736``` 2737 2738### delete 2739 2740delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) 2741 2742Deletes KV pairs from this KV store. This API uses an asynchronous callback to return the result. 2743 2744**Model restriction**: This API can be used only in the stage model. 2745 2746**System API**: This is a system API. 2747 2748**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 2749 2750**Parameters** 2751 2752| Name | Type | Mandatory| Description | 2753| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | 2754| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| 2755| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 2756 2757**Error codes** 2758 2759For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2760 2761| ID| **Error Message** | 2762| ------------ | -------------------------------------- | 2763| 15100003 | Database corrupted. | 2764| 15100005 | Database or result set already closed. | 2765 2766For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). 2767 2768| ID| **Error Message** | 2769| ------------ | -------------------------------------------- | 2770| 14800047 | The WAL file size exceeds the default limit. | 2771 2772**Example** 2773 2774```ts 2775import dataSharePredicates from '@ohos.data.dataSharePredicates'; 2776import { BusinessError } from '@ohos.base'; 2777 2778try { 2779 let predicates = new dataSharePredicates.DataSharePredicates(); 2780 let arr = ["name"]; 2781 predicates.inKeys(arr); 2782 kvStore.put("name", "bob", (err) => { 2783 if (err != undefined) { 2784 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 2785 return; 2786 } 2787 console.info("Succeeded in putting"); 2788 if (kvStore != null) { 2789 kvStore.delete(predicates, (err) => { 2790 if (err == undefined) { 2791 console.info('Succeeded in deleting'); 2792 } else { 2793 console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); 2794 } 2795 }); 2796 } 2797 }); 2798} catch (e) { 2799 let error = e as BusinessError; 2800 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 2801} 2802``` 2803 2804### delete 2805 2806delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> 2807 2808Deletes KV pairs from this KV store. This API uses a promise to return the result. 2809 2810**Model restriction**: This API can be used only in the stage model. 2811 2812**System API**: This is a system API. 2813 2814**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 2815 2816**Parameters** 2817 2818| Name | Type | Mandatory| Description | 2819| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | 2820| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| 2821 2822**Return value** 2823 2824| Type | Description | 2825| ------------------- | ------------------------- | 2826| Promise<void> | Promise that returns no value.| 2827 2828**Error codes** 2829 2830For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2831 2832| ID| **Error Message** | 2833| ------------ | ---------------------------------------- | 2834| 15100003 | Database corrupted. | 2835| 15100005 | Database or result set already closed. | 2836 2837For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). 2838 2839| ID| **Error Message** | 2840| ------------ | -------------------------------------------- | 2841| 14800047 | The WAL file size exceeds the default limit. | 2842 2843**Example** 2844 2845```ts 2846import dataSharePredicates from '@ohos.data.dataSharePredicates'; 2847import { BusinessError } from '@ohos.base'; 2848 2849try { 2850 let predicates = new dataSharePredicates.DataSharePredicates(); 2851 let arr = ["name"]; 2852 predicates.inKeys(arr); 2853 kvStore.put("name", "bob").then(() => { 2854 console.info(`Succeeded in putting data`); 2855 if (kvStore != null) { 2856 kvStore.delete(predicates).then(() => { 2857 console.info('Succeeded in deleting'); 2858 }).catch((err: BusinessError) => { 2859 console.error(`Failed to delete.code is ${err.code},message is ${err.message}`); 2860 }); 2861 } 2862 }).catch((err: BusinessError) => { 2863 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 2864 }); 2865} catch (e) { 2866 let error = e as BusinessError; 2867 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 2868} 2869``` 2870 2871### deleteBatch 2872 2873deleteBatch(keys: string[], callback: AsyncCallback<void>): void 2874 2875Batch deletes KV pairs from this single KV store. This API uses an asynchronous callback to return the result. 2876 2877**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2878 2879**Parameters** 2880 2881| Name | Type | Mandatory| Description | 2882| -------- | ------------------------- | ---- | ------------------------ | 2883| keys | string[] | Yes | KV pairs to delete in batches.| 2884| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 2885 2886**Error codes** 2887 2888For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2889 2890| ID| **Error Message** | 2891| ------------ | ---------------------------------------- | 2892| 15100003 | Database corrupted. | 2893| 15100005 | Database or result set already closed. | 2894 2895For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). 2896 2897| ID| **Error Message** | 2898| ------------ | -------------------------------------------- | 2899| 14800047 | The WAL file size exceeds the default limit. | 2900 2901**Example** 2902 2903```ts 2904import { BusinessError } from '@ohos.base'; 2905 2906try { 2907 let entries: distributedKVStore.Entry[] = []; 2908 let keys: string[] = []; 2909 for (let i = 0; i < 5; i++) { 2910 let key = 'batch_test_string_key'; 2911 let entry: distributedKVStore.Entry = { 2912 key: key + i, 2913 value: { 2914 type: distributedKVStore.ValueType.STRING, 2915 value: 'batch_test_string_value' 2916 } 2917 } 2918 entries.push(entry); 2919 keys.push(key + i); 2920 } 2921 console.info(`entries: ${entries}`); 2922 kvStore.putBatch(entries, async (err) => { 2923 if (err != undefined) { 2924 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 2925 return; 2926 } 2927 console.info('Succeeded in putting Batch'); 2928 if (kvStore != null) { 2929 kvStore.deleteBatch(keys, async (err) => { 2930 if (err != undefined) { 2931 console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`); 2932 return; 2933 } 2934 console.info('Succeeded in deleting Batch'); 2935 }); 2936 } 2937 }); 2938} catch (e) { 2939 let error = e as BusinessError; 2940 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 2941} 2942``` 2943 2944### deleteBatch 2945 2946deleteBatch(keys: string[]): Promise<void> 2947 2948Batch deletes KV pairs from this single KV store. This API uses a promise to return the result. 2949 2950**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 2951 2952**Parameters** 2953 2954| Name| Type| Mandatory| Description | 2955| ------ | -------- | ---- | ------------------------ | 2956| keys | string[] | Yes | KV pairs to delete in batches.| 2957 2958**Return value** 2959 2960| Type | Description | 2961| ------------------- | ------------------------- | 2962| Promise<void> | Promise that returns no value.| 2963 2964**Error codes** 2965 2966For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 2967 2968| ID| **Error Message** | 2969| ------------ | ---------------------------------------- | 2970| 15100003 | Database corrupted. | 2971| 15100005 | Database or result set already closed. | 2972 2973For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). 2974 2975| ID| **Error Message** | 2976| ------------ | -------------------------------------------- | 2977| 14800047 | The WAL file size exceeds the default limit. | 2978 2979**Example** 2980 2981```ts 2982import { BusinessError } from '@ohos.base'; 2983 2984try { 2985 let entries: distributedKVStore.Entry[] = []; 2986 let keys: string[] = []; 2987 for (let i = 0; i < 5; i++) { 2988 let key = 'batch_test_string_key'; 2989 let entry: distributedKVStore.Entry = { 2990 key: key + i, 2991 value: { 2992 type: distributedKVStore.ValueType.STRING, 2993 value: 'batch_test_string_value' 2994 } 2995 } 2996 entries.push(entry); 2997 keys.push(key + i); 2998 } 2999 console.info(`entries: ${entries}`); 3000 kvStore.putBatch(entries).then(async () => { 3001 console.info('Succeeded in putting Batch'); 3002 if (kvStore != null) { 3003 kvStore.deleteBatch(keys).then(() => { 3004 console.info('Succeeded in deleting Batch'); 3005 }).catch((err: BusinessError) => { 3006 console.error(`Failed to delete Batch.code is ${err.code},message is ${err.message}`); 3007 }); 3008 } 3009 }).catch((err: BusinessError) => { 3010 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 3011 }); 3012} catch (e) { 3013 let error = e as BusinessError; 3014 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 3015} 3016``` 3017 3018### removeDeviceData 3019 3020removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void 3021 3022Deletes data of a device. This API uses an asynchronous callback to return the result. 3023> **NOTE** 3024> 3025> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 3026> For details about how to obtain **deviceId**, see [sync()](#sync). 3027 3028**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 3029 3030**Parameters** 3031 3032| Name | Type | Mandatory| Description | 3033| -------- | ------------------------- | ---- | ---------------------- | 3034| deviceId | string | Yes | ID of the target device.| 3035| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 3036 3037**Error codes** 3038 3039For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3040 3041| ID| **Error Message** | 3042| ------------ | -------------------------------------- | 3043| 15100005 | Database or result set already closed. | 3044 3045**Example** 3046 3047```ts 3048import { BusinessError } from '@ohos.base'; 3049 3050const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 3051const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; 3052try { 3053 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async (err) => { 3054 console.info('Succeeded in putting data'); 3055 const deviceid = 'no_exist_device_id'; 3056 if (kvStore != null) { 3057 kvStore.removeDeviceData(deviceid, async (err) => { 3058 if (err == undefined) { 3059 console.info('succeeded in removing device data'); 3060 } else { 3061 console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `); 3062 if (kvStore != null) { 3063 kvStore.get(KEY_TEST_STRING_ELEMENT, async (err, data) => { 3064 console.info('Succeeded in getting data'); 3065 }); 3066 } 3067 } 3068 }); 3069 } 3070 }); 3071} catch (e) { 3072 let error = e as BusinessError; 3073 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`) 3074} 3075``` 3076 3077### removeDeviceData 3078 3079removeDeviceData(deviceId: string): Promise<void> 3080 3081Deletes data of a device. This API uses a promise to return the result. 3082> **NOTE** 3083> 3084> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 3085> For details about how to obtain **deviceId**, see [sync()](#sync). 3086 3087**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 3088 3089**Parameters** 3090 3091| Name | Type| Mandatory| Description | 3092| -------- | -------- | ---- | ---------------------- | 3093| deviceId | string | Yes | ID of the target device.| 3094 3095**Return value** 3096 3097| Type | Description | 3098| ------------------- | ------------------------- | 3099| Promise<void> | Promise that returns no value.| 3100 3101**Error codes** 3102 3103For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3104 3105| ID| **Error Message** | 3106| ------------ | -------------------------------------- | 3107| 15100005 | Database or result set already closed. | 3108 3109**Example** 3110 3111```ts 3112import { BusinessError } from '@ohos.base'; 3113 3114const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 3115const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; 3116try { 3117 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { 3118 console.info('Succeeded in putting data'); 3119 }).catch((err: BusinessError) => { 3120 console.error(`Failed to put data.code is ${err.code},message is ${err.message} `); 3121 }); 3122 const deviceid = 'no_exist_device_id'; 3123 kvStore.removeDeviceData(deviceid).then(() => { 3124 console.info('succeeded in removing device data'); 3125 }).catch((err: BusinessError) => { 3126 console.error(`Failed to remove device data.code is ${err.code},message is ${err.message} `); 3127 }); 3128 kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { 3129 console.info('Succeeded in getting data'); 3130 }).catch((err: BusinessError) => { 3131 console.error(`Failed to get data.code is ${err.code},message is ${err.message} `); 3132 }); 3133} catch (e) { 3134 let error = e as BusinessError; 3135 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`) 3136} 3137``` 3138 3139### get 3140 3141get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 3142 3143Obtains the value of the specified key. This API uses an asynchronous callback to return the result. 3144 3145**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3146 3147**Parameters** 3148 3149| Name | Type| Mandatory | Description | 3150| ----- | ------ | ---- | ----------------------- | 3151| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | 3152| callback |AsyncCallback<boolean \| string \| number \| Uint8Array> | Yes |Callback invoked to return the value obtained. | 3153 3154**Error codes** 3155 3156For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3157 3158| ID| **Error Message** | 3159| ------------ | -------------------------------------- | 3160| 15100003 | Database corrupted. | 3161| 15100004 | Not found. | 3162| 15100005 | Database or result set already closed. | 3163 3164**Example** 3165 3166```ts 3167import { BusinessError } from '@ohos.base'; 3168 3169 3170const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 3171const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 3172try { 3173 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => { 3174 if (err != undefined) { 3175 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 3176 return; 3177 } 3178 console.info("Succeeded in putting"); 3179 if (kvStore != null) { 3180 kvStore.get(KEY_TEST_STRING_ELEMENT, (err, data) => { 3181 if (err != undefined) { 3182 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 3183 return; 3184 } 3185 console.info(`Succeeded in getting data.data=${data}`); 3186 }); 3187 } 3188 }); 3189} catch (e) { 3190 let error = e as BusinessError; 3191 console.error(`Failed to get.code is ${error.code},message is ${error.message}`); 3192} 3193``` 3194 3195### get 3196 3197get(key: string): Promise<boolean | string | number | Uint8Array> 3198 3199Obtains the value of the specified key. This API uses a promise to return the result. 3200 3201**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3202 3203**Parameters** 3204 3205| Name| Type| Mandatory| Description | 3206| ------ | -------- | ---- | ------------------------------------------------------------ | 3207| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 3208 3209**Return value** 3210 3211| Type | Description | 3212| ------ | ------- | 3213|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.| 3214 3215**Error codes** 3216 3217For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3218 3219| ID| **Error Message** | 3220| ------------ | -------------------------------------- | 3221| 15100003 | Database corrupted. | 3222| 15100004 | Not found. | 3223| 15100005 | Database or result set already closed. | 3224 3225**Example** 3226 3227```ts 3228import { BusinessError } from '@ohos.base'; 3229 3230 3231const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 3232const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 3233try { 3234 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { 3235 console.info(`Succeeded in putting data`); 3236 if (kvStore != null) { 3237 kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { 3238 console.info(`Succeeded in getting data.data=${data}`); 3239 }).catch((err: BusinessError) => { 3240 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 3241 }); 3242 } 3243 }).catch((err: BusinessError) => { 3244 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 3245 }); 3246} catch (e) { 3247 let error = e as BusinessError; 3248 console.error(`Failed to get.code is ${error.code},message is ${error.message}`); 3249} 3250``` 3251 3252### getEntries 3253 3254getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void 3255 3256Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. 3257 3258**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3259 3260**Parameters** 3261 3262| Name | Type | Mandatory| Description | 3263| --------- | -------------------------------------- | ---- | ---------------------------------------- | 3264| keyPrefix | string | Yes | Key prefix to match. | 3265| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs that match the specified prefix.| 3266 3267**Error codes** 3268 3269For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3270 3271| ID| **Error Message** | 3272| ------------ | -------------------------------------- | 3273| 15100003 | Database corrupted. | 3274| 15100005 | Database or result set already closed. | 3275 3276**Example** 3277 3278```ts 3279import { BusinessError } from '@ohos.base'; 3280 3281try { 3282 let entries: distributedKVStore.Entry[] = []; 3283 for (let i = 0; i < 10; i++) { 3284 let key = 'batch_test_string_key'; 3285 let entry: distributedKVStore.Entry = { 3286 key: key + i, 3287 value: { 3288 type: distributedKVStore.ValueType.STRING, 3289 value: 'batch_test_string_value' 3290 } 3291 } 3292 entries.push(entry); 3293 } 3294 console.info(`entries: ${entries}`); 3295 kvStore.putBatch(entries, async (err) => { 3296 if (err != undefined) { 3297 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 3298 return; 3299 } 3300 console.info('Succeeded in putting Batch'); 3301 if (kvStore != null) { 3302 kvStore.getEntries('batch_test_string_key', (err, entries) => { 3303 if (err != undefined) { 3304 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 3305 return; 3306 } 3307 console.info('Succeeded in getting Entries'); 3308 console.info(`entries.length: ${entries.length}`); 3309 console.info(`entries[0]: ${entries[0]}`); 3310 }); 3311 } 3312 }); 3313} catch (e) { 3314 let error = e as BusinessError; 3315 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `); 3316} 3317``` 3318 3319### getEntries 3320 3321getEntries(keyPrefix: string): Promise<Entry[]> 3322 3323Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result. 3324 3325**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3326 3327**Parameters** 3328 3329| Name | Type| Mandatory| Description | 3330| --------- | -------- | ---- | -------------------- | 3331| keyPrefix | string | Yes | Key prefix to match.| 3332 3333**Return value** 3334 3335| Type | Description | 3336| -------------------------------- | ------------------------------------------- | 3337| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified prefix.| 3338 3339**Error codes** 3340 3341For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3342 3343| ID| **Error Message** | 3344| ------------ | -------------------------------------- | 3345| 15100003 | Database corrupted. | 3346| 15100005 | Database or result set already closed. | 3347 3348**Example** 3349 3350```ts 3351import { BusinessError } from '@ohos.base'; 3352 3353 3354try { 3355 let entries: distributedKVStore.Entry[] = []; 3356 for (let i = 0; i < 10; i++) { 3357 let key = 'batch_test_string_key'; 3358 let entry: distributedKVStore.Entry = { 3359 key: key + i, 3360 value: { 3361 type: distributedKVStore.ValueType.STRING, 3362 value: 'batch_test_string_value' 3363 } 3364 } 3365 entries.push(entry); 3366 } 3367 console.info(`entries: ${entries}`); 3368 kvStore.putBatch(entries).then(async () => { 3369 console.info('Succeeded in putting Batch'); 3370 if (kvStore != null) { 3371 kvStore.getEntries('batch_test_string_key').then((entries) => { 3372 console.info('Succeeded in getting Entries'); 3373 console.info(`PutBatch ${entries}`); 3374 }).catch((err: BusinessError) => { 3375 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 3376 }); 3377 } 3378 }).catch((err: BusinessError) => { 3379 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 3380 }); 3381} catch (e) { 3382 let error = e as BusinessError; 3383 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `); 3384} 3385``` 3386 3387### getEntries 3388 3389getEntries(query: Query, callback: AsyncCallback<Entry[]>): void 3390 3391Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result. 3392 3393**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3394 3395**Parameters** 3396 3397| Name | Type | Mandatory| Description | 3398| -------- | -------------------------------------- | ---- | ----------------------------------------------- | 3399| query | [Query](#query) | Yes | Key prefix to match. | 3400| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs that match the specified **Query** object.| 3401 3402**Error codes** 3403 3404For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3405 3406| ID| **Error Message** | 3407| ------------ | -------------------------------------- | 3408| 15100003 | Database corrupted. | 3409| 15100005 | Database or result set already closed. | 3410 3411**Example** 3412 3413```ts 3414import { BusinessError } from '@ohos.base'; 3415 3416try { 3417 let arr = new Uint8Array([21, 31]); 3418 let entries: distributedKVStore.Entry[] = []; 3419 for (let i = 0; i < 10; i++) { 3420 let key = 'batch_test_bool_key'; 3421 let entry: distributedKVStore.Entry = { 3422 key: key + i, 3423 value: { 3424 type: distributedKVStore.ValueType.BYTE_ARRAY, 3425 value: arr 3426 } 3427 } 3428 entries.push(entry); 3429 } 3430 console.info(`entries: {entries}`); 3431 kvStore.putBatch(entries, async (err) => { 3432 console.info('Succeeded in putting Batch'); 3433 const query = new distributedKVStore.Query(); 3434 query.prefixKey("batch_test"); 3435 if (kvStore != null) { 3436 kvStore.getEntries(query, (err, entries) => { 3437 if (err != undefined) { 3438 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 3439 return; 3440 } 3441 console.info('Succeeded in getting Entries'); 3442 console.info(`entries.length: ${entries.length}`); 3443 console.info(`entries[0]: ${entries[0]}`); 3444 }); 3445 } 3446 }); 3447} catch (e) { 3448 let error = e as BusinessError; 3449 console.error(`Failed to get Entries.code is ${error.code},message is ${error.message}`); 3450} 3451``` 3452 3453### getEntries 3454 3455getEntries(query: Query): Promise<Entry[]> 3456 3457Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result. 3458 3459**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3460 3461**Parameters** 3462 3463| Name| Type | Mandatory| Description | 3464| ------ | -------------- | ---- | -------------- | 3465| query | [Query](#query) | Yes | **Query** object to match.| 3466 3467**Return value** 3468 3469| Type | Description | 3470| -------------------------------- | -------------------------------------------------- | 3471| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified **Query** object.| 3472 3473**Error codes** 3474 3475For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3476 3477| ID| **Error Message** | 3478| ------------ | -------------------------------------- | 3479| 15100003 | Database corrupted. | 3480| 15100005 | Database or result set already closed. | 3481 3482**Example** 3483 3484```ts 3485import { BusinessError } from '@ohos.base'; 3486 3487try { 3488 let arr = new Uint8Array([21, 31]); 3489 let entries: distributedKVStore.Entry[] = []; 3490 for (let i = 0; i < 10; i++) { 3491 let key = 'batch_test_bool_key'; 3492 let entry: distributedKVStore.Entry = { 3493 key: key + i, 3494 value: { 3495 type: distributedKVStore.ValueType.BYTE_ARRAY, 3496 value: arr 3497 } 3498 } 3499 entries.push(entry); 3500 } 3501 console.info(`entries: {entries}`); 3502 kvStore.putBatch(entries).then(async () => { 3503 console.info('Succeeded in putting Batch'); 3504 const query = new distributedKVStore.Query(); 3505 query.prefixKey("batch_test"); 3506 if (kvStore != null) { 3507 kvStore.getEntries(query).then((entries) => { 3508 console.info('Succeeded in getting Entries'); 3509 }).catch((err: BusinessError) => { 3510 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 3511 }); 3512 } 3513 }).catch((err: BusinessError) => { 3514 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`) 3515 }); 3516 console.info('Succeeded in getting Entries'); 3517} catch (e) { 3518 let error = e as BusinessError; 3519 console.error(`Failed to get Entries.code is ${error.code},message is ${error.message}`); 3520} 3521``` 3522 3523### getResultSet 3524 3525getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void 3526 3527Obtains a result set with the specified prefix from this single KV store. This API uses an asynchronous callback to return the result. 3528 3529**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3530 3531**Parameters** 3532 3533| Name | Type | Mandatory| Description | 3534| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | 3535| keyPrefix | string | Yes | Key prefix to match. | 3536| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the result set with the specified prefix.| 3537 3538**Error codes** 3539 3540For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3541 3542| ID| **Error Message** | 3543| ------------ | -------------------------------------- | 3544| 15100001 | Over max limits. | 3545| 15100003 | Database corrupted. | 3546| 15100005 | Database or result set already closed. | 3547 3548 3549**Example** 3550 3551```ts 3552import { BusinessError } from '@ohos.base'; 3553 3554try { 3555 let resultSet: distributedKVStore.KVStoreResultSet; 3556 let entries: distributedKVStore.Entry[] = []; 3557 for (let i = 0; i < 10; i++) { 3558 let key = 'batch_test_string_key'; 3559 let entry: distributedKVStore.Entry = { 3560 key: key + i, 3561 value: { 3562 type: distributedKVStore.ValueType.STRING, 3563 value: 'batch_test_string_value' 3564 } 3565 } 3566 entries.push(entry); 3567 } 3568 kvStore.putBatch(entries, async (err) => { 3569 if (err != undefined) { 3570 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 3571 return; 3572 } 3573 console.info('Succeeded in putting batch'); 3574 if (kvStore != null) { 3575 kvStore.getResultSet('batch_test_string_key', async (err, result) => { 3576 if (err != undefined) { 3577 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3578 return; 3579 } 3580 console.info('Succeeded in getting result set'); 3581 resultSet = result; 3582 if (kvStore != null) { 3583 kvStore.closeResultSet(resultSet, (err) => { 3584 if (err != undefined) { 3585 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 3586 return; 3587 } 3588 console.info('Succeeded in closing result set'); 3589 }); 3590 } 3591 }); 3592 } 3593 }); 3594} catch (e) { 3595 let error = e as BusinessError; 3596 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 3597} 3598``` 3599 3600### getResultSet 3601 3602getResultSet(keyPrefix: string): Promise<KVStoreResultSet> 3603 3604Obtains a result set with the specified prefix from this single KV store. This API uses a promise to return the result. 3605 3606**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3607 3608**Parameters** 3609 3610| Name | Type| Mandatory| Description | 3611| --------- | -------- | ---- | -------------------- | 3612| keyPrefix | string | Yes | Key prefix to match.| 3613 3614**Return value** 3615 3616| Type | Description | 3617| ---------------------------------------------------- | --------------------------------------- | 3618| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the result set with the specified prefix.| 3619 3620**Error codes** 3621 3622For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3623 3624| ID| **Error Message** | 3625| ------------ | -------------------------------------- | 3626| 15100001 | Over max limits. | 3627| 15100003 | Database corrupted. | 3628| 15100005 | Database or result set already closed. | 3629 3630**Example** 3631 3632```ts 3633import { BusinessError } from '@ohos.base'; 3634 3635try { 3636 let resultSet: distributedKVStore.KVStoreResultSet; 3637 let entries: distributedKVStore.Entry[] = []; 3638 for (let i = 0; i < 10; i++) { 3639 let key = 'batch_test_string_key'; 3640 let entry: distributedKVStore.Entry = { 3641 key: key + i, 3642 value: { 3643 type: distributedKVStore.ValueType.STRING, 3644 value: 'batch_test_string_value' 3645 } 3646 } 3647 entries.push(entry); 3648 } 3649 kvStore.putBatch(entries).then(async () => { 3650 console.info('Succeeded in putting batch'); 3651 }).catch((err: BusinessError) => { 3652 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 3653 }); 3654 kvStore.getResultSet('batch_test_string_key').then((result) => { 3655 console.info('Succeeded in getting result set'); 3656 resultSet = result; 3657 if (kvStore != null) { 3658 kvStore.closeResultSet(resultSet).then(() => { 3659 console.info('Succeeded in closing result set'); 3660 }).catch((err: BusinessError) => { 3661 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 3662 }); 3663 } 3664 }).catch((err: BusinessError) => { 3665 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3666 }); 3667} catch (e) { 3668 let error = e as BusinessError; 3669 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 3670} 3671``` 3672 3673### getResultSet 3674 3675getResultSet(query: Query, callback: AsyncCallback<KVStoreResultSet>): void 3676 3677Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. 3678 3679**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3680 3681**Parameters** 3682 3683| Name | Type | Mandatory| Description | 3684| -------- | ---------------------------------------------------------- | ---- | --------------------------------------------------------- | 3685| query | Query | Yes | **Query** object to match. | 3686| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| 3687 3688**Error codes** 3689 3690For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3691 3692| ID| **Error Message** | 3693| ------------ | -------------------------------------- | 3694| 15100001 | Over max limits. | 3695| 15100003 | Database corrupted. | 3696| 15100005 | Database or result set already closed. | 3697 3698**Example** 3699 3700```ts 3701import { BusinessError } from '@ohos.base'; 3702 3703try { 3704 let resultSet: distributedKVStore.KVStoreResultSet; 3705 let entries: distributedKVStore.Entry[] = []; 3706 for (let i = 0; i < 10; i++) { 3707 let key = 'batch_test_string_key'; 3708 let entry: distributedKVStore.Entry = { 3709 key: key + i, 3710 value: { 3711 type: distributedKVStore.ValueType.STRING, 3712 value: 'batch_test_string_value' 3713 } 3714 } 3715 entries.push(entry); 3716 } 3717 kvStore.putBatch(entries, async (err) => { 3718 if (err != undefined) { 3719 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 3720 return; 3721 } 3722 console.info('Succeeded in putting batch'); 3723 const query = new distributedKVStore.Query(); 3724 query.prefixKey("batch_test"); 3725 if (kvStore != null) { 3726 kvStore.getResultSet(query, async (err, result) => { 3727 if (err != undefined) { 3728 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3729 return; 3730 } 3731 console.info('Succeeded in getting result set'); 3732 }); 3733 } 3734 }); 3735} catch (e) { 3736 let error = e as BusinessError; 3737 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 3738} 3739``` 3740 3741### getResultSet 3742 3743getResultSet(query: Query): Promise<KVStoreResultSet> 3744 3745Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. 3746 3747**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3748 3749**Parameters** 3750 3751| Name| Type | Mandatory| Description | 3752| ------ | -------------- | ---- | -------------- | 3753| query | [Query](#query) | Yes | **Query** object to match.| 3754 3755**Return value** 3756 3757| Type | Description | 3758| ---------------------------------------------------- | ------------------------------------------------------------ | 3759| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| 3760 3761**Error codes** 3762 3763For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3764 3765| ID| **Error Message** | 3766| ------------ | -------------------------------------- | 3767| 15100001 | Over max limits. | 3768| 15100003 | Database corrupted. | 3769| 15100005 | Database or result set already closed. | 3770 3771**Example** 3772 3773```ts 3774import { BusinessError } from '@ohos.base'; 3775 3776try { 3777 let resultSet: distributedKVStore.KVStoreResultSet; 3778 let entries: distributedKVStore.Entry[] = []; 3779 for (let i = 0; i < 10; i++) { 3780 let key = 'batch_test_string_key'; 3781 let entry: distributedKVStore.Entry = { 3782 key: key + i, 3783 value: { 3784 type: distributedKVStore.ValueType.STRING, 3785 value: 'batch_test_string_value' 3786 } 3787 } 3788 entries.push(entry); 3789 } 3790 kvStore.putBatch(entries).then(async () => { 3791 console.info('Succeeded in putting batch'); 3792 }).catch((err: BusinessError) => { 3793 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 3794 }); 3795 const query = new distributedKVStore.Query(); 3796 query.prefixKey("batch_test"); 3797 kvStore.getResultSet(query).then((result) => { 3798 console.info('Succeeded in getting result set'); 3799 resultSet = result; 3800 }).catch((err: BusinessError) => { 3801 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3802 }); 3803} catch (e) { 3804 let error = e as BusinessError; 3805 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 3806} 3807``` 3808 3809### getResultSet 3810 3811getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void 3812 3813Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses an asynchronous callback to return the result. 3814 3815**Model restriction**: This API can be used only in the stage model. 3816 3817**System API**: This is a system API. 3818 3819**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 3820 3821**Parameters** 3822 3823| Name | Type | Mandatory| Description | 3824| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 3825| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | 3826| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| 3827 3828**Error codes** 3829 3830For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3831 3832| ID| **Error Message** | 3833| ------------ | -------------------------------------- | 3834| 15100001 | Over max limits. | 3835| 15100003 | Database corrupted. | 3836| 15100005 | Database or result set already closed. | 3837 3838**Example** 3839 3840```ts 3841import dataSharePredicates from '@ohos.data.dataSharePredicates'; 3842import { BusinessError } from '@ohos.base'; 3843 3844try { 3845 let resultSet: distributedKVStore.KVStoreResultSet; 3846 let predicates = new dataSharePredicates.DataSharePredicates(); 3847 predicates.prefixKey("batch_test_string_key"); 3848 kvStore.getResultSet(predicates, async (err, result) => { 3849 if (err != undefined) { 3850 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3851 return; 3852 } 3853 console.info('Succeeded in getting result set'); 3854 resultSet = result; 3855 if (kvStore != null) { 3856 kvStore.closeResultSet(resultSet, (err) => { 3857 if (err != undefined) { 3858 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 3859 return; 3860 } 3861 console.info('Succeeded in closing result set'); 3862 }); 3863 } 3864 }); 3865} catch (e) { 3866 let error = e as BusinessError; 3867 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 3868} 3869``` 3870 3871### getResultSet 3872 3873getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> 3874 3875Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses a promise to return the result. 3876 3877**Model restriction**: This API can be used only in the stage model. 3878 3879**System API**: This is a system API. 3880 3881**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 3882 3883**Parameters** 3884 3885| Name | Type | Mandatory| Description | 3886| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | 3887| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| 3888 3889**Return value** 3890 3891| Type | Description | 3892| ---------------------------------------------------- | ------------------------- | 3893| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| 3894 3895**Error codes** 3896 3897For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 3898 3899| ID| **Error Message** | 3900| ------------ | -------------------------------------- | 3901| 15100001 | Over max limits. | 3902| 15100003 | Database corrupted. | 3903| 15100005 | Database or result set already closed. | 3904 3905**Example** 3906 3907```ts 3908import dataSharePredicates from '@ohos.data.dataSharePredicates'; 3909import { BusinessError } from '@ohos.base'; 3910 3911try { 3912 let resultSet: distributedKVStore.KVStoreResultSet; 3913 let predicates = new dataSharePredicates.DataSharePredicates(); 3914 predicates.prefixKey("batch_test_string_key"); 3915 kvStore.getResultSet(predicates).then((result) => { 3916 console.info('Succeeded in getting result set'); 3917 resultSet = result; 3918 if (kvStore != null) { 3919 kvStore.closeResultSet(resultSet).then(() => { 3920 console.info('Succeeded in closing result set'); 3921 }).catch((err: BusinessError) => { 3922 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 3923 }); 3924 } 3925 }).catch((err: BusinessError) => { 3926 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3927 }); 3928 3929} catch (e) { 3930 let error = e as BusinessError; 3931 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 3932} 3933``` 3934 3935### closeResultSet 3936 3937closeResultSet(resultSet: KVStoreResultSet, callback: AsyncCallback<void>): void 3938 3939Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). This API uses an asynchronous callback to return the result. 3940 3941**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 3942 3943**Parameters** 3944 3945| Name | Type | Mandatory| Description | 3946| --------- | ------------------------------------- | ---- | ---------------------------------- | 3947| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes | **KVStoreResultSet** object to close.| 3948| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 3949 3950**Example** 3951 3952```ts 3953import { BusinessError } from '@ohos.base'; 3954 3955let resultSet: distributedKVStore.KVStoreResultSet; 3956try { 3957 kvStore.getResultSet('batch_test_string_key', async (err, result) => { 3958 if (err != undefined) { 3959 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 3960 return; 3961 } 3962 console.info('Succeeded in getting result set'); 3963 resultSet = result; 3964 if (kvStore != null) { 3965 kvStore.closeResultSet(resultSet, (err) => { 3966 if (err != undefined) { 3967 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 3968 return; 3969 } 3970 console.info('Succeeded in closing result set'); 3971 }) 3972 } 3973 }); 3974} catch (e) { 3975 let error = e as BusinessError; 3976 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 3977} 3978 3979``` 3980 3981### closeResultSet 3982 3983closeResultSet(resultSet: KVStoreResultSet): Promise<void> 3984 3985Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). 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| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes | **KVStoreResultSet** object to close.| 3994 3995**Return value** 3996 3997| Type | Description | 3998| ------------------- | ------------------------- | 3999| Promise<void> | Promise that returns no value.| 4000 4001**Example** 4002 4003```ts 4004import { BusinessError } from '@ohos.base'; 4005 4006let resultSet: distributedKVStore.KVStoreResultSet; 4007try { 4008 kvStore.getResultSet('batch_test_string_key').then((result) => { 4009 console.info('Succeeded in getting result set'); 4010 resultSet = result; 4011 if (kvStore != null) { 4012 kvStore.closeResultSet(resultSet).then(() => { 4013 console.info('Succeeded in closing result set'); 4014 }).catch((err: BusinessError) => { 4015 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 4016 }); 4017 } 4018 }).catch((err: BusinessError) => { 4019 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 4020 }); 4021 4022} catch (e) { 4023 let error = e as BusinessError; 4024 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 4025} 4026``` 4027 4028### getResultSize 4029 4030getResultSize(query: Query, callback: AsyncCallback<number>): void 4031 4032Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result. 4033 4034**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4035 4036**Parameters** 4037 4038| Name | Type | Mandatory| Description | 4039| -------- | --------------------------- | ---- | ------------------------------------------- | 4040| query | [Query](#query) | Yes | **Query** object to match. | 4041| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| 4042 4043**Error codes** 4044 4045For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4046 4047| ID| **Error Message** | 4048| ------------ | -------------------------------------- | 4049| 15100003 | Database corrupted. | 4050| 15100005 | Database or result set already closed. | 4051 4052**Example** 4053 4054```ts 4055import { BusinessError } from '@ohos.base'; 4056 4057try { 4058 let entries: distributedKVStore.Entry[] = []; 4059 for (let i = 0; i < 10; i++) { 4060 let key = 'batch_test_string_key'; 4061 let entry: distributedKVStore.Entry = { 4062 key: key + i, 4063 value: { 4064 type: distributedKVStore.ValueType.STRING, 4065 value: 'batch_test_string_value' 4066 } 4067 } 4068 entries.push(entry); 4069 } 4070 kvStore.putBatch(entries, async (err) => { 4071 console.info('Succeeded in putting batch'); 4072 const query = new distributedKVStore.Query(); 4073 query.prefixKey("batch_test"); 4074 if (kvStore != null) { 4075 kvStore.getResultSize(query, async (err, resultSize) => { 4076 if (err != undefined) { 4077 console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); 4078 return; 4079 } 4080 console.info('Succeeded in getting result set size'); 4081 }); 4082 } 4083 }); 4084} catch (e) { 4085 let error = e as BusinessError; 4086 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 4087} 4088``` 4089 4090### getResultSize 4091 4092getResultSize(query: Query): Promise<number> 4093 4094Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result. 4095 4096**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4097 4098**Parameters** 4099 4100| Name| Type | Mandatory| Description | 4101| ------ | -------------- | ---- | -------------- | 4102| query | [Query](#query) | Yes | **Query** object to match.| 4103 4104**Return value** 4105 4106| Type | Description | 4107| --------------------- | ----------------------------------------------- | 4108| Promise<number> | Promise used to return the number of results obtained.| 4109 4110**Error codes** 4111 4112For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4113 4114| ID| **Error Message** | 4115| ------------ | -------------------------------------- | 4116| 15100003 | Database corrupted. | 4117| 15100005 | Database or result set already closed. | 4118 4119**Example** 4120 4121```ts 4122import { BusinessError } from '@ohos.base'; 4123 4124try { 4125 let entries: distributedKVStore.Entry[] = []; 4126 for (let i = 0; i < 10; i++) { 4127 let key = 'batch_test_string_key'; 4128 let entry: distributedKVStore.Entry = { 4129 key: key + i, 4130 value: { 4131 type: distributedKVStore.ValueType.STRING, 4132 value: 'batch_test_string_value' 4133 } 4134 } 4135 entries.push(entry); 4136 } 4137 kvStore.putBatch(entries).then(async () => { 4138 console.info('Succeeded in putting batch'); 4139 }).catch((err: BusinessError) => { 4140 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 4141 }); 4142 const query = new distributedKVStore.Query(); 4143 query.prefixKey("batch_test"); 4144 kvStore.getResultSize(query).then((resultSize) => { 4145 console.info('Succeeded in getting result set size'); 4146 }).catch((err: BusinessError) => { 4147 console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); 4148 }); 4149} catch (e) { 4150 let error = e as BusinessError; 4151 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 4152} 4153``` 4154 4155### backup 4156 4157backup(file:string, callback: AsyncCallback<void>):void 4158 4159Backs up a distributed KV store. This API uses an asynchronous callback to return the result. 4160 4161**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4162 4163**Parameters** 4164 4165| Name | Type | Mandatory| Description | 4166| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 4167| file | string | Yes | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 4168| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4169 4170**Error codes** 4171 4172For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4173 4174| ID| **Error Message** | 4175| ------------ | -------------------------------------- | 4176| 15100005 | Database or result set already closed. | 4177 4178**Example** 4179 4180```ts 4181import { BusinessError } from '@ohos.base'; 4182 4183let file = "BK001"; 4184try { 4185 kvStore.backup(file, (err) => { 4186 if (err) { 4187 console.error(`Failed to backup.code is ${err.code},message is ${err.message} `); 4188 } else { 4189 console.info(`Succeeded in backupping data`); 4190 } 4191 }); 4192} catch (e) { 4193 let error = e as BusinessError; 4194 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4195} 4196``` 4197 4198### backup 4199 4200backup(file:string): Promise<void> 4201 4202Backs up an RDB store. This API uses a promise to return the result. 4203 4204**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4205 4206**Parameters** 4207 4208| Name| Type| Mandatory| Description | 4209| ------ | -------- | ---- | ------------------------------------------------------------ | 4210| file | string | Yes | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 4211 4212**Return value** 4213 4214| Type | Description | 4215| ------------------- | ------------------------- | 4216| Promise<void> | Promise that returns no value.| 4217 4218**Error codes** 4219 4220For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4221 4222| ID| **Error Message** | 4223| ------------ | -------------------------------------- | 4224| 15100005 | Database or result set already closed. | 4225 4226**Example** 4227 4228```ts 4229import { BusinessError } from '@ohos.base'; 4230 4231let file = "BK001"; 4232try { 4233 kvStore.backup(file).then(() => { 4234 console.info(`Succeeded in backupping data`); 4235 }).catch((err: BusinessError) => { 4236 console.error(`Failed to backup.code is ${err.code},message is ${err.message}`); 4237 }); 4238} catch (e) { 4239 let error = e as BusinessError; 4240 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4241} 4242``` 4243 4244### restore 4245 4246restore(file:string, callback: AsyncCallback<void>):void 4247 4248Restores a distributed KV store from a database file. This API uses an asynchronous callback to return the result. 4249 4250**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4251 4252**Parameters** 4253 4254| Name | Type | Mandatory| Description | 4255| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 4256| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 4257| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4258 4259**Error codes** 4260 4261For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4262 4263| ID| **Error Message** | 4264| ------------ | -------------------------------------- | 4265| 15100005 | Database or result set already closed. | 4266 4267**Example** 4268 4269```ts 4270import { BusinessError } from '@ohos.base'; 4271 4272let file = "BK001"; 4273try { 4274 kvStore.restore(file, (err) => { 4275 if (err) { 4276 console.error(`Failed to restore.code is ${err.code},message is ${err.message}`); 4277 } else { 4278 console.info(`Succeeded in restoring data`); 4279 } 4280 }); 4281} catch (e) { 4282 let error = e as BusinessError; 4283 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4284} 4285``` 4286 4287### restore 4288 4289restore(file:string): Promise<void> 4290 4291Restores a distributed KV store from a database file. This API uses a promise to return the result. 4292 4293**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4294 4295**Parameters** 4296 4297| Name| Type| Mandatory| Description | 4298| ------ | -------- | ---- | ------------------------------------------------------------ | 4299| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 4300 4301**Return value** 4302 4303| Type | Description | 4304| ------------------- | ------------------------- | 4305| Promise<void> | Promise that returns no value.| 4306 4307**Error codes** 4308 4309For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4310 4311| ID| **Error Message** | 4312| ------------ | -------------------------------------- | 4313| 15100005 | Database or result set already closed. | 4314 4315**Example** 4316 4317```ts 4318import { BusinessError } from '@ohos.base'; 4319 4320let file = "BK001"; 4321try { 4322 kvStore.restore(file).then(() => { 4323 console.info(`Succeeded in restoring data`); 4324 }).catch((err: BusinessError) => { 4325 console.error(`Failed to restore.code is ${err.code},message is ${err.message}`); 4326 }); 4327} catch (e) { 4328 let error = e as BusinessError; 4329 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4330} 4331``` 4332 4333### deleteBackup 4334 4335deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[string, number]>>):void 4336 4337Deletes a backup file. This API uses an asynchronous callback to return the result. 4338 4339**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4340 4341**Parameters** 4342 4343| Name | Type | Mandatory| Description | 4344| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | 4345| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 4346| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to return the name of the backup file deleted and the operation result. | 4347 4348**Example** 4349 4350```ts 4351import { BusinessError } from '@ohos.base'; 4352 4353let files = ["BK001", "BK002"]; 4354try { 4355 kvStore.deleteBackup(files, (err, data) => { 4356 if (err) { 4357 console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`); 4358 } else { 4359 console.info(`Succeed in deleting Backup.data=${data}`); 4360 } 4361 }); 4362} catch (e) { 4363 let error = e as BusinessError; 4364 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4365} 4366``` 4367 4368### deleteBackup 4369 4370deleteBackup(files:Array<string>): Promise<Array<[string, number]>> 4371 4372Deletes a backup file. This API uses a promise to return the result. 4373 4374**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4375 4376**Parameters** 4377 4378| Name| Type | Mandatory| Description | 4379| ------ | ------------------- | ---- | ------------------------------------------------------------ | 4380| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| 4381 4382**Return value** 4383 4384| Type | Description | 4385| -------------------------------------------- | ----------------------------------------------- | 4386| Promise<Array<[string, number]>> | Promise used to return the name of the backup file deleted and the operation result.| 4387 4388**Example** 4389 4390```ts 4391import { BusinessError } from '@ohos.base'; 4392 4393let files = ["BK001", "BK002"]; 4394try { 4395 kvStore.deleteBackup(files).then((data) => { 4396 console.info(`Succeed in deleting Backup.data=${data}`); 4397 }).catch((err: BusinessError) => { 4398 console.error(`Failed to delete Backup.code is ${err.code},message is ${err.message}`); 4399 }) 4400} catch (e) { 4401 let error = e as BusinessError; 4402 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4403} 4404``` 4405 4406### startTransaction 4407 4408startTransaction(callback: AsyncCallback<void>): void 4409 4410Starts the transaction in this single KV store. This API uses an asynchronous callback to return the result. 4411 4412**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4413 4414**Parameters** 4415 4416| Name | Type | Mandatory| Description | 4417| -------- | ------------------------- | ---- | ---------- | 4418| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| 4419 4420**Error codes** 4421 4422For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4423 4424| ID| **Error Message** | 4425| ------------ | ---------------------------------------- | 4426| 15100005 | Database or result set already closed. | 4427 4428For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). 4429 4430| ID| **Error Message** | 4431| ------------ | -------------------------------------------- | 4432| 14800047 | The WAL file size exceeds the default limit. | 4433 4434**Example** 4435 4436```ts 4437import { BusinessError } from '@ohos.base'; 4438 4439function putBatchString(len: number, prefix: string) { 4440 let entries: distributedKVStore.Entry[] = []; 4441 for (let i = 0; i < len; i++) { 4442 let entry: distributedKVStore.Entry = { 4443 key: prefix + i, 4444 value: { 4445 type: distributedKVStore.ValueType.STRING, 4446 value: 'batch_test_string_value' 4447 } 4448 } 4449 entries.push(entry); 4450 } 4451 return entries; 4452} // Custom function used outside the scope to prevent syntax check errors. 4453 4454try { 4455 let count = 0; 4456 kvStore.on('dataChange', 0, (data) => { 4457 console.info(`startTransaction 0 ${data}`); 4458 count++; 4459 }); 4460 kvStore.startTransaction(async (err) => { 4461 if (err != undefined) { 4462 console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`); 4463 return; 4464 } 4465 console.info('Succeeded in starting Transaction'); 4466 let entries = putBatchString(10, 'batch_test_string_key'); 4467 console.info(`entries: ${entries}`); 4468 if (kvStore != null) { 4469 kvStore.putBatch(entries, async (err) => { 4470 if (err != undefined) { 4471 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 4472 return; 4473 } 4474 console.info('Succeeded in putting Batch'); 4475 }); 4476 } 4477 }); 4478} catch (e) { 4479 let error = e as BusinessError; 4480 console.error(`Failed to start Transaction.code is ${error.code},message is ${error.message}`); 4481} 4482``` 4483 4484### startTransaction 4485 4486startTransaction(): Promise<void> 4487 4488Starts the transaction in this single KV store. This API uses a promise to return the result. 4489 4490**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4491 4492**Return value** 4493 4494| Type | Description | 4495| ------------------- | ------------------------- | 4496| Promise<void> | Promise that returns no value.| 4497 4498**Error codes** 4499 4500For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4501 4502| ID| **Error Message** | 4503| ------------ | ---------------------------------------- | 4504| 15100005 | Database or result set already closed. | 4505 4506For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). 4507 4508| ID| **Error Message** | 4509| ------------ | -------------------------------------------- | 4510| 14800047 | The WAL file size exceeds the default limit. | 4511 4512**Example** 4513 4514```ts 4515import { BusinessError } from '@ohos.base'; 4516 4517try { 4518 let count = 0; 4519 kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, (data) => { 4520 console.info(`startTransaction 0 ${data}`); 4521 count++; 4522 }); 4523 kvStore.startTransaction().then(async () => { 4524 console.info('Succeeded in starting Transaction'); 4525 }).catch((err: BusinessError) => { 4526 console.error(`Failed to start Transaction.code is ${err.code},message is ${err.message}`); 4527 }); 4528} catch (e) { 4529 let error = e as BusinessError; 4530 console.error(`Failed to start Transaction.code is ${error.code},message is ${error.message}`); 4531} 4532``` 4533 4534### commit 4535 4536commit(callback: AsyncCallback<void>): void 4537 4538Commits the transaction in this single KV store. This API uses an asynchronous callback to return the result. 4539 4540**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4541 4542**Parameters** 4543 4544| Name | Type | Mandatory| Description | 4545| -------- | ------------------------- | ---- | ---------- | 4546| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| 4547 4548**Error codes** 4549 4550For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4551 4552| ID| **Error Message** | 4553| ------------ | -------------------------------------- | 4554| 15100005 | Database or result set already closed. | 4555 4556**Example** 4557 4558```ts 4559import { BusinessError } from '@ohos.base'; 4560 4561try { 4562 kvStore.commit((err) => { 4563 if (err == undefined) { 4564 console.info('Succeeded in committing'); 4565 } else { 4566 console.error(`Failed to commit.code is ${err.code},message is ${err.message}`); 4567 } 4568 }); 4569} catch (e) { 4570 let error = e as BusinessError; 4571 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4572} 4573``` 4574 4575### commit 4576 4577commit(): Promise<void> 4578 4579Commits the transaction in this single KV store. This API uses a promise to return the result. 4580 4581**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4582 4583**Return value** 4584 4585| Type | Description | 4586| ------------------- | ------------------------- | 4587| Promise<void> | Promise that returns no value.| 4588 4589**Error codes** 4590 4591For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4592 4593| ID| **Error Message** | 4594| ------------ | -------------------------------------- | 4595| 15100005 | Database or result set already closed. | 4596 4597**Example** 4598 4599```ts 4600import { BusinessError } from '@ohos.base'; 4601 4602try { 4603 kvStore.commit().then(async () => { 4604 console.info('Succeeded in committing'); 4605 }).catch((err: BusinessError) => { 4606 console.error(`Failed to commit.code is ${err.code},message is ${err.message}`); 4607 }); 4608} catch (e) { 4609 let error = e as BusinessError; 4610 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4611} 4612``` 4613 4614### rollback 4615 4616rollback(callback: AsyncCallback<void>): void 4617 4618Rolls back the transaction in this single KV store. This API uses an asynchronous callback to return the result. 4619 4620**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4621 4622**Parameters** 4623 4624| Name | Type | Mandatory| Description | 4625| -------- | ------------------------- | ---- | ---------- | 4626| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| 4627 4628**Error codes** 4629 4630For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4631 4632| ID| **Error Message** | 4633| ------------ | -------------------------------------- | 4634| 15100005 | Database or result set already closed. | 4635 4636**Example** 4637 4638```ts 4639import { BusinessError } from '@ohos.base'; 4640 4641try { 4642 kvStore.rollback((err) => { 4643 if (err == undefined) { 4644 console.info('Succeeded in rolling back'); 4645 } else { 4646 console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`); 4647 } 4648 }); 4649} catch (e) { 4650 let error = e as BusinessError; 4651 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4652} 4653``` 4654 4655### rollback 4656 4657rollback(): Promise<void> 4658 4659Rolls back the transaction in this single KV store. This API uses a promise to return the result. 4660 4661**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4662 4663**Return value** 4664 4665| Type | Description | 4666| ------------------- | ------------------------- | 4667| Promise<void> | Promise that returns no value.| 4668 4669**Error codes** 4670 4671For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4672 4673| ID| **Error Message** | 4674| ------------ | -------------------------------------- | 4675| 15100005 | Database or result set already closed. | 4676 4677**Example** 4678 4679```ts 4680import { BusinessError } from '@ohos.base'; 4681 4682try { 4683 kvStore.rollback().then(async () => { 4684 console.info('Succeeded in rolling back'); 4685 }).catch((err: BusinessError) => { 4686 console.error(`Failed to rollback.code is ${err.code},message is ${err.message}`); 4687 }); 4688} catch (e) { 4689 let error = e as BusinessError; 4690 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4691} 4692``` 4693 4694### enableSync 4695 4696enableSync(enabled: boolean, callback: AsyncCallback<void>): void 4697 4698Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result. 4699 4700**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4701 4702**Parameters** 4703 4704| Name | Type | Mandatory| Description | 4705| -------- | ------------------------- | ---- | --------------------------------------------------------- | 4706| enabled | boolean | Yes | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.| 4707| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 4708 4709**Example** 4710 4711```ts 4712import { BusinessError } from '@ohos.base'; 4713 4714try { 4715 kvStore.enableSync(true, (err) => { 4716 if (err == undefined) { 4717 console.info('Succeeded in enabling sync'); 4718 } else { 4719 console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`); 4720 } 4721 }); 4722} catch (e) { 4723 let error = e as BusinessError; 4724 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4725} 4726``` 4727 4728### enableSync 4729 4730enableSync(enabled: boolean): Promise<void> 4731 4732Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result. 4733 4734**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4735 4736**Parameters** 4737 4738| Name | Type| Mandatory| Description | 4739| ------- | -------- | ---- | --------------------------------------------------------- | 4740| enabled | boolean | Yes | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.| 4741 4742**Return value** 4743 4744| Type | Description | 4745| ------------------- | ------------------------- | 4746| Promise<void> | Promise that returns no value.| 4747 4748**Example** 4749 4750```ts 4751import { BusinessError } from '@ohos.base'; 4752 4753try { 4754 kvStore.enableSync(true).then(() => { 4755 console.info('Succeeded in enabling sync'); 4756 }).catch((err: BusinessError) => { 4757 console.error(`Failed to enable sync.code is ${err.code},message is ${err.message}`); 4758 }); 4759} catch (e) { 4760 let error = e as BusinessError; 4761 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4762} 4763``` 4764 4765### setSyncRange 4766 4767setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void 4768 4769Sets the data synchronization range. This API uses an asynchronous callback to return the result. 4770 4771**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4772 4773**Parameters** 4774 4775| Name | Type | Mandatory| Description | 4776| ------------------- | ------------------------- | ---- | -------------------------------- | 4777| localLabels | string[] | Yes | Synchronization labels set for the local device. | 4778| remoteSupportLabels | string[] | Yes | Synchronization labels set for remote devices.| 4779| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 4780 4781**Example** 4782 4783```ts 4784import { BusinessError } from '@ohos.base'; 4785 4786try { 4787 const localLabels = ['A', 'B']; 4788 const remoteSupportLabels = ['C', 'D']; 4789 kvStore.setSyncRange(localLabels, remoteSupportLabels, (err) => { 4790 if (err != undefined) { 4791 console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`); 4792 return; 4793 } 4794 console.info('Succeeded in setting syncRange'); 4795 }); 4796} catch (e) { 4797 let error = e as BusinessError; 4798 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4799} 4800``` 4801 4802### setSyncRange 4803 4804setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void> 4805 4806Sets the data synchronization range. This API uses a promise to return the result. 4807 4808**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4809 4810**Parameters** 4811 4812| Name | Type| Mandatory| Description | 4813| ------------------- | -------- | ---- | -------------------------------- | 4814| localLabels | string[] | Yes | Synchronization labels set for the local device. | 4815| remoteSupportLabels | string[] | Yes | Synchronization labels set for remote devices.| 4816 4817**Return value** 4818 4819| Type | Description | 4820| ------------------- | ------------------------- | 4821| Promise<void> | Promise that returns no value.| 4822 4823**Example** 4824 4825```ts 4826import { BusinessError } from '@ohos.base'; 4827 4828try { 4829 const localLabels = ['A', 'B']; 4830 const remoteSupportLabels = ['C', 'D']; 4831 kvStore.setSyncRange(localLabels, remoteSupportLabels).then(() => { 4832 console.info('Succeeded in setting syncRange'); 4833 }).catch((err: BusinessError) => { 4834 console.error(`Failed to set syncRange.code is ${err.code},message is ${err.message}`); 4835 }); 4836} catch (e) { 4837 let error = e as BusinessError; 4838 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4839} 4840``` 4841 4842### setSyncParam 4843 4844setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void 4845 4846Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result. 4847 4848**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4849 4850**Parameters** 4851 4852| Name | Type | Mandatory| Description | 4853| --------------------- | ------------------------- | ---- | -------------------------------------------- | 4854| defaultAllowedDelayMs | number | Yes | Default delay allowed for database synchronization, in ms.| 4855| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | 4856 4857**Example** 4858 4859```ts 4860import { BusinessError } from '@ohos.base'; 4861 4862try { 4863 const defaultAllowedDelayMs = 500; 4864 kvStore.setSyncParam(defaultAllowedDelayMs, (err) => { 4865 if (err != undefined) { 4866 console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`); 4867 return; 4868 } 4869 console.info('Succeeded in setting syncParam'); 4870 }); 4871} catch (e) { 4872 let error = e as BusinessError; 4873 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4874} 4875``` 4876 4877### setSyncParam 4878 4879setSyncParam(defaultAllowedDelayMs: number): Promise<void> 4880 4881Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result. 4882 4883**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4884 4885**Parameters** 4886 4887| Name | Type| Mandatory| Description | 4888| --------------------- | -------- | ---- | -------------------------------------------- | 4889| defaultAllowedDelayMs | number | Yes | Default delay allowed for database synchronization, in ms.| 4890 4891**Return value** 4892 4893| Type | Description | 4894| ------------------- | ------------------------- | 4895| Promise<void> | Promise that returns no value.| 4896 4897**Example** 4898 4899```ts 4900import { BusinessError } from '@ohos.base'; 4901 4902try { 4903 const defaultAllowedDelayMs = 500; 4904 kvStore.setSyncParam(defaultAllowedDelayMs).then(() => { 4905 console.info('Succeeded in setting syncParam'); 4906 }).catch((err: BusinessError) => { 4907 console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`); 4908 }); 4909} catch (e) { 4910 let error = e as BusinessError; 4911 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4912} 4913``` 4914 4915### sync 4916 4917sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void 4918 4919Synchronizes the KV store manually. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). 4920> **NOTE** 4921> 4922> **deviceIds** is **networkId** in [DeviceBasicInfo](js-apis-distributedDeviceManager.md#devicebasicinfo), which can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 4923 4924**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 4925 4926**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4927 4928**Parameters** 4929 4930| Name | Type | Mandatory| Description | 4931| --------- | --------------------- | ---- | ---------------------------------------------- | 4932| deviceIds | string[] | Yes | List of **networkId**s of the devices in the same networking environment to be synchronized.| 4933| mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | 4934| delayMs | number | No | Allowed synchronization delay time, in ms. The default value is **0**. | 4935 4936**Error codes** 4937 4938For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 4939 4940| ID| **Error Message** | 4941| ------------ | ------------------- | 4942| 15100003 | Database corrupted. | 4943| 15100004 | Not found. | 4944 4945**Example** 4946 4947```ts 4948import deviceManager from '@ohos.distributedDeviceManager'; 4949import UIAbility from '@ohos.app.ability.UIAbility'; 4950import { BusinessError } from '@ohos.base'; 4951 4952let devManager: deviceManager.DeviceManager; 4953const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; 4954const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; 4955// create deviceManager 4956export default class EntryAbility extends UIAbility { 4957 onCreate() { 4958 let context = this.context; 4959 try { 4960 devManager = deviceManager.createDeviceManager(context.applicationInfo.name); 4961 let deviceIds: string[] = []; 4962 if (devManager != null) { 4963 let devices = devManager.getAvailableDeviceListSync(); 4964 for (let i = 0; i < devices.length; i++) { 4965 deviceIds[i] = devices[i].networkId as string; 4966 } 4967 } 4968 try { 4969 if (kvStore != null) { 4970 kvStore.on('syncComplete', (data) => { 4971 console.info('Sync dataChange'); 4972 }); 4973 if (kvStore != null) { 4974 kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, (err) => { 4975 if (err != undefined) { 4976 console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); 4977 return; 4978 } 4979 console.info('Succeeded in putting data'); 4980 const mode = distributedKVStore.SyncMode.PULL_ONLY; 4981 if (kvStore != null) { 4982 kvStore.sync(deviceIds, mode, 1000); 4983 } 4984 }); 4985 } 4986 } 4987 } catch (e) { 4988 let error = e as BusinessError; 4989 console.error(`Failed to sync.code is ${error.code},message is ${error.message}`); 4990 } 4991 4992 } catch (err) { 4993 let error = err as BusinessError; 4994 console.error("createDeviceManager errCode:" + error.code + ",errMessage:" + error.message); 4995 } 4996 } 4997} 4998``` 4999 5000### sync 5001 5002sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void 5003 5004Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). 5005> **NOTE** 5006> 5007> **deviceIds** is **networkId** in [DeviceBasicInfo](js-apis-distributedDeviceManager.md#devicebasicinfo), which can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 5008 5009**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 5010 5011**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5012 5013**Parameters** 5014 5015| Name | Type | Mandatory| Description | 5016| --------- | --------------------- | ---- | ---------------------------------------------- | 5017| deviceIds | string[] | Yes | List of **networkId**s of the devices in the same networking environment to be synchronized.| 5018| mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | 5019| query | [Query](#query) | Yes | **Query** object to match. | 5020| delayMs | number | No | Allowed synchronization delay time, in ms. The default value is **0**.| 5021 5022**Error codes** 5023 5024For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5025 5026| ID| **Error Message** | 5027| ------------ | ------------------- | 5028| 15100003 | Database corrupted. | 5029| 15100004 | Not found. | 5030 5031**Example** 5032 5033```ts 5034import deviceManager from '@ohos.distributedDeviceManager'; 5035import UIAbility from '@ohos.app.ability.UIAbility'; 5036import { BusinessError } from '@ohos.base'; 5037 5038let devManager: deviceManager.DeviceManager; 5039const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; 5040const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; 5041// create deviceManager 5042export default class EntryAbility extends UIAbility { 5043 onCreate() { 5044 let context = this.context; 5045 try { 5046 let devManager = deviceManager.createDeviceManager(context.applicationInfo.name); 5047 let deviceIds: string[] = []; 5048 if (devManager != null) { 5049 let devices = devManager.getAvailableDeviceListSync(); 5050 for (let i = 0; i < devices.length; i++) { 5051 deviceIds[i] = devices[i].networkId as string; 5052 } 5053 } 5054 try { 5055 if (kvStore != null) { 5056 kvStore.on('syncComplete', (data) => { 5057 console.info('Sync dataChange'); 5058 }); 5059 if (kvStore != null) { 5060 kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, (err) => { 5061 if (err != undefined) { 5062 console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); 5063 return; 5064 } 5065 console.info('Succeeded in putting data'); 5066 const mode = distributedKVStore.SyncMode.PULL_ONLY; 5067 const query = new distributedKVStore.Query(); 5068 query.prefixKey("batch_test"); 5069 query.deviceId(devManager.getLocalDeviceNetworkId()); 5070 if (kvStore != null) { 5071 kvStore.sync(deviceIds, query, mode, 1000); 5072 } 5073 }); 5074 } 5075 } 5076 } catch (e) { 5077 let error = e as BusinessError; 5078 console.error(`Failed to sync.code is ${error.code},message is ${error.message}`); 5079 } 5080 5081 } catch (err) { 5082 let error = err as BusinessError; 5083 console.error("createDeviceManager errCode:" + error.code + ",errMessage:" + error.message); 5084 } 5085 } 5086} 5087``` 5088 5089### on('dataChange') 5090 5091on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void 5092 5093Subscribes to data changes of the specified type. 5094 5095**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5096 5097**Parameters** 5098 5099| Name | Type | Mandatory| Description | 5100| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | 5101| event | string | Yes | Event type. The value is **dataChange**, which indicates data changes. | 5102| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | 5103| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the data change. | 5104 5105**Error codes** 5106 5107For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5108 5109| ID| **Error Message** | 5110| ------------ | -------------------------------------- | 5111| 15100001 | Over max limits. | 5112| 15100005 | Database or result set already closed. | 5113 5114**Example** 5115 5116```ts 5117import { BusinessError } from '@ohos.base'; 5118 5119try { 5120 kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, (data) => { 5121 console.info(`dataChange callback call data: ${data}`); 5122 }); 5123} catch (e) { 5124 let error = e as BusinessError; 5125 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 5126} 5127``` 5128 5129### on('syncComplete') 5130 5131on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void 5132 5133Subscribes to synchronization complete events. 5134 5135**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5136 5137**Parameters** 5138 5139| Name | Type | Mandatory| Description | 5140| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | 5141| event | string | Yes | Event type. The value is **syncComplete**, which indicates a synchronization complete event.| 5142| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return the synchronization complete event. | 5143 5144**Example** 5145 5146```ts 5147import { BusinessError } from '@ohos.base'; 5148 5149 5150const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; 5151const VALUE_TEST_FLOAT_ELEMENT = 321.12; 5152try { 5153 kvStore.on('syncComplete', (data) => { 5154 console.info(`syncComplete ${data}`); 5155 }); 5156 kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then(() => { 5157 console.info('succeeded in putting'); 5158 }).catch((err: BusinessError) => { 5159 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 5160 }); 5161} catch (e) { 5162 let error = e as BusinessError; 5163 console.error(`Failed to subscribe syncComplete.code is ${error.code},message is ${error.message}`); 5164} 5165``` 5166 5167### off('dataChange') 5168 5169off(event:'dataChange', listener?: Callback<ChangeNotification>): void 5170 5171Unsubscribes from data changes. 5172 5173**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5174 5175**Parameters** 5176 5177| Name | Type | Mandatory| Description | 5178| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | 5179| event | string | Yes | Event type. The value is **dataChange**, which indicates data changes. | 5180| listener | Callback<[ChangeNotification](#changenotification)> | No | Callback for the data change. If the callback is not specified, all callbacks for **dataChange** will be unregistered. | 5181 5182**Error codes** 5183 5184For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5185 5186| ID| **Error Message** | 5187| ------------ | -------------------------------------- | 5188| 15100005 | Database or result set already closed. | 5189 5190**Example** 5191 5192```ts 5193import { BusinessError } from '@ohos.base'; 5194 5195class KvstoreModel { 5196 call(data: distributedKVStore.ChangeNotification) { 5197 console.info(`dataChange : ${data}`); 5198 } 5199 5200 subscribeDataChange() { 5201 try { 5202 if (kvStore != null) { 5203 kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); 5204 } 5205 } catch (err) { 5206 let error = err as BusinessError; 5207 console.error(`Failed to subscribeDataChange.code is ${error.code},message is ${error.message}`); 5208 } 5209 } 5210 5211 unsubscribeDataChange() { 5212 try { 5213 if (kvStore != null) { 5214 kvStore.off('dataChange', this.call); 5215 } 5216 } catch (err) { 5217 let error = err as BusinessError; 5218 console.error(`Failed to unsubscribeDataChange.code is ${error.code},message is ${error.message}`); 5219 } 5220 } 5221} 5222``` 5223 5224### off('syncComplete') 5225 5226off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void 5227 5228Unsubscribes from synchronization complete events. 5229 5230**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5231 5232**Parameters** 5233 5234| Name | Type | Mandatory| Description | 5235| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | 5236| event | string | Yes | Event type. The value is **syncComplete**, which indicates a synchronization complete event.| 5237| syncCallback | Callback<Array<[string, number]>> | No | Callback for the synchronization complete event. If the callback is not specified, all callbacks for **syncComplete** will be unregistered. | 5238 5239**Example** 5240 5241```ts 5242import { BusinessError } from '@ohos.base'; 5243 5244class KvstoreModel { 5245 call(data: [string, number][]) { 5246 console.info(`syncComplete : ${data}`); 5247 } 5248 5249 subscribeDataChange() { 5250 try { 5251 if (kvStore != null) { 5252 kvStore.on('syncComplete', this.call); 5253 } 5254 } catch (err) { 5255 let error = err as BusinessError; 5256 console.error(`Failed to subscribeDataChange.code is ${error.code},message is ${error.message}`); 5257 } 5258 } 5259 5260 unsubscribeDataChange() { 5261 try { 5262 if (kvStore != null) { 5263 kvStore.off('syncComplete', this.call); 5264 } 5265 } catch (err) { 5266 let error = err as BusinessError; 5267 console.error(`Failed to unsubscribeDataChange.code is ${error.code},message is ${error.message}`); 5268 } 5269 } 5270} 5271``` 5272 5273### getSecurityLevel 5274 5275getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void 5276 5277Obtains the security level of this KV store. This API uses an asynchronous callback to return the result. 5278 5279**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5280 5281**Parameters** 5282 5283| Name | Type | Mandatory| Description | 5284| -------- | ---------------------------------------------------- | ---- | -------------------------------- | 5285| callback | AsyncCallback<[SecurityLevel](#securitylevel)> | Yes | Callback invoked to return the security level obtained.| 5286 5287**Error codes** 5288 5289For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5290 5291| ID| **Error Message** | 5292| ------------ | -------------------------------------- | 5293| 15100005 | Database or result set already closed. | 5294 5295**Example** 5296 5297```ts 5298import { BusinessError } from '@ohos.base'; 5299 5300try { 5301 kvStore.getSecurityLevel((err, data) => { 5302 if (err != undefined) { 5303 console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`); 5304 return; 5305 } 5306 console.info('Succeeded in getting securityLevel'); 5307 }); 5308} catch (e) { 5309 let error = e as BusinessError; 5310 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 5311} 5312``` 5313 5314### getSecurityLevel 5315 5316getSecurityLevel(): Promise<SecurityLevel> 5317 5318Obtains the security level of this KV store. This API uses a promise to return the result. 5319 5320**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5321 5322**Return value** 5323 5324| Type | Description | 5325| ---------------------------------------------- | ----------------------------------- | 5326| Promise<[SecurityLevel](#securitylevel)> | Promise used to return the security level obtained.| 5327 5328**Error codes** 5329 5330For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5331 5332| ID| **Error Message** | 5333| ------------ | -------------------------------------- | 5334| 15100005 | Database or result set already closed. | 5335 5336**Example** 5337 5338```ts 5339import { BusinessError } from '@ohos.base'; 5340 5341try { 5342 kvStore.getSecurityLevel().then((data) => { 5343 console.info('Succeeded in getting securityLevel'); 5344 }).catch((err: BusinessError) => { 5345 console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`); 5346 }); 5347} catch (e) { 5348 let error = e as BusinessError; 5349 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 5350} 5351``` 5352 5353## DeviceKVStore 5354 5355Provides APIs for querying and synchronizing data in a device KV store. This class inherits from **SingleKVStore**. 5356 5357Data 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. 5358 5359For 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. 5360 5361Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. 5362 5363### get 5364 5365get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 5366 5367Obtains the value of the specified key for this device. This API uses an asynchronous callback to return the result. 5368 5369**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5370 5371**Parameters** 5372 5373| Name | Type | Mandatory| Description | 5374| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 5375| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 5376| callback | AsyncCallback<boolean \| string \| number \| Uint8Array> | Yes | Callback invoked to return the value obtained. | 5377 5378**Error codes** 5379 5380For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5381 5382| ID| **Error Message** | 5383| ------------ | -------------------------------------- | 5384| 15100003 | Database corrupted. | 5385| 15100004 | Not found. | 5386| 15100005 | Database or result set already closed. | 5387 5388**Example** 5389 5390```ts 5391import { BusinessError } from '@ohos.base'; 5392 5393const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 5394const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 5395try { 5396 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => { 5397 if (err != undefined) { 5398 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 5399 return; 5400 } 5401 console.info("Succeeded in putting"); 5402 if (kvStore != null) { 5403 kvStore.get(KEY_TEST_STRING_ELEMENT, (err, data) => { 5404 if (err != undefined) { 5405 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 5406 return; 5407 } 5408 console.info(`Succeeded in getting data.data=${data}`); 5409 }); 5410 } 5411 }); 5412} catch (e) { 5413 let error = e as BusinessError; 5414 console.error(`Failed to get.code is ${error.code},message is ${error.message}`); 5415} 5416``` 5417 5418### get 5419 5420get(key: string): Promise<boolean | string | number | Uint8Array> 5421 5422Obtains the value of the specified key for this device. This API uses a promise to return the result. 5423 5424**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5425 5426**Parameters** 5427 5428| Name| Type | Mandatory| Description | 5429| ------ | ------ | ---- | ------------------------------------------------------------ | 5430| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 5431 5432**Return value** 5433 5434| Type | Description | 5435| -------------------------------------------------------- | ------------------------------- | 5436| Promise<Uint8Array \| string \| boolean \| number> | Promise used to return the value obtained.| 5437 5438**Error codes** 5439 5440For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5441 5442| ID| **Error Message** | 5443| ------------ | -------------------------------------- | 5444| 15100003 | Database corrupted. | 5445| 15100004 | Not found. | 5446| 15100005 | Database or result set already closed. | 5447 5448**Example** 5449 5450```ts 5451import { BusinessError } from '@ohos.base'; 5452 5453const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 5454const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 5455try { 5456 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { 5457 console.info(`Succeeded in putting data`); 5458 if (kvStore != null) { 5459 kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { 5460 console.info(`Succeeded in getting data.data=${data}`); 5461 }).catch((err: BusinessError) => { 5462 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 5463 }); 5464 } 5465 }).catch((err: BusinessError) => { 5466 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 5467 }); 5468} catch (e) { 5469 let error = e as BusinessError; 5470 console.error(`Failed to get.code is ${error.code},message is ${error.message}`); 5471} 5472``` 5473 5474### get 5475 5476get(deviceId: string, key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 5477 5478Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. 5479> **NOTE** 5480> 5481> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 5482> For details about how to obtain **deviceId**, see [sync()](#sync). 5483 5484**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5485 5486**Parameters** 5487 5488| Name | Type| Mandatory | Description | 5489| ----- | ------ | ---- | ----------------------- | 5490| deviceId |string | Yes |ID of the target device. | 5491| key |string | Yes |Key to match. | 5492| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback invoked to return the value obtained. | 5493 5494**Error codes** 5495 5496For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5497 5498| ID| **Error Message** | 5499| ------------ | -------------------------------------- | 5500| 15100003 | Database corrupted. | 5501| 15100004 | Not found. | 5502| 15100005 | Database or result set already closed. | 5503 5504**Example** 5505 5506```ts 5507import { BusinessError } from '@ohos.base'; 5508 5509const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 5510const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; 5511try { 5512 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async (err) => { 5513 if (err != undefined) { 5514 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 5515 return; 5516 } 5517 console.info('Succeeded in putting'); 5518 if (kvStore != null) { 5519 kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, (err, data) => { 5520 if (err != undefined) { 5521 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 5522 return; 5523 } 5524 console.info('Succeeded in getting'); 5525 }); 5526 } 5527 }) 5528} catch (e) { 5529 let error = e as BusinessError; 5530 console.error(`Failed to get.code is ${error.code},message is ${error.message}`); 5531} 5532``` 5533 5534### get 5535 5536get(deviceId: string, key: string): Promise<boolean | string | number | Uint8Array> 5537 5538Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. 5539> **NOTE** 5540> 5541> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 5542> For details about how to obtain **deviceId**, see [sync()](#sync). 5543 5544**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5545 5546**Parameters** 5547 5548| Name | Type| Mandatory| Description | 5549| -------- | -------- | ---- | ------------------------ | 5550| deviceId | string | Yes | ID of the target device.| 5551| key | string | Yes | Key to match. | 5552 5553**Return value** 5554 5555| Type | Description | 5556| ------ | ------- | 5557|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value that matches the given condition.| 5558 5559**Error codes** 5560 5561For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5562 5563| ID| **Error Message** | 5564| ------------ | -------------------------------------- | 5565| 15100003 | Database corrupted. | 5566| 15100004 | Not found. | 5567| 15100005 | Database or result set already closed. | 5568 5569**Example** 5570 5571```ts 5572import { BusinessError } from '@ohos.base'; 5573 5574const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 5575const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; 5576try { 5577 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async () => { 5578 console.info('Succeeded in putting'); 5579 if (kvStore != null) { 5580 kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { 5581 console.info('Succeeded in getting'); 5582 }).catch((err: BusinessError) => { 5583 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 5584 }); 5585 } 5586 }).catch((error: BusinessError) => { 5587 console.error(`Failed to put.code is ${error.code},message is ${error.message}`); 5588 }); 5589} catch (e) { 5590 let error = e as BusinessError; 5591 console.error(`Failed to get.code is ${error.code},message is ${error.message}`); 5592} 5593``` 5594 5595### getEntries 5596 5597getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void 5598 5599Obtains all KV pairs that match the specified key prefix for this device. This API uses an asynchronous callback to return the result. 5600 5601**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5602 5603**Parameters** 5604 5605| Name | Type | Mandatory| Description | 5606| --------- | -------------------------------------- | ---- | ---------------------------------------- | 5607| keyPrefix | string | Yes | Key prefix to match. | 5608| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs that match the specified prefix.| 5609 5610**Error codes** 5611 5612For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5613 5614| ID| **Error Message** | 5615| ------------ | -------------------------------------- | 5616| 15100003 | Database corrupted. | 5617| 15100005 | Database or result set already closed. | 5618 5619**Example** 5620 5621```ts 5622import { BusinessError } from '@ohos.base'; 5623 5624try { 5625 let entries: distributedKVStore.Entry[] = []; 5626 for (let i = 0; i < 10; i++) { 5627 let key = 'batch_test_string_key'; 5628 let entry: distributedKVStore.Entry = { 5629 key: key + i, 5630 value: { 5631 type: distributedKVStore.ValueType.STRING, 5632 value: 'batch_test_string_value' 5633 } 5634 } 5635 entries.push(entry); 5636 } 5637 console.info(`entries: ${entries}`); 5638 kvStore.putBatch(entries, async (err) => { 5639 if (err != undefined) { 5640 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 5641 return; 5642 } 5643 console.info('Succeeded in putting Batch'); 5644 if (kvStore != null) { 5645 kvStore.getEntries('batch_test_string_key', (err, entries) => { 5646 if (err != undefined) { 5647 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 5648 return; 5649 } 5650 console.info('Succeeded in getting Entries'); 5651 console.info(`entries.length: ${entries.length}`); 5652 console.info(`entries[0]: ${entries[0]}`); 5653 }); 5654 } 5655 }); 5656} catch (e) { 5657 let error = e as BusinessError; 5658 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `); 5659} 5660``` 5661 5662### getEntries 5663 5664getEntries(keyPrefix: string): Promise<Entry[]> 5665 5666Obtains all KV pairs that match the specified key prefix for this device. This API uses a promise to return the result. 5667 5668**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5669 5670**Parameters** 5671 5672| Name | Type | Mandatory| Description | 5673| --------- | ------ | ---- | -------------------- | 5674| keyPrefix | string | Yes | Key prefix to match.| 5675 5676**Return value** 5677 5678| Type | Description | 5679| -------------------------------- | ------------------------------------------- | 5680| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified prefix.| 5681 5682**Error codes** 5683 5684For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5685 5686| ID| **Error Message** | 5687| ------------ | -------------------------------------- | 5688| 15100003 | Database corrupted. | 5689| 15100005 | Database or result set already closed. | 5690 5691**Example** 5692 5693```ts 5694import { BusinessError } from '@ohos.base'; 5695 5696try { 5697 let entries: distributedKVStore.Entry[] = []; 5698 for (let i = 0; i < 10; i++) { 5699 let key = 'batch_test_string_key'; 5700 let entry: distributedKVStore.Entry = { 5701 key: key + i, 5702 value: { 5703 type: distributedKVStore.ValueType.STRING, 5704 value: 'batch_test_string_value' 5705 } 5706 } 5707 entries.push(entry); 5708 } 5709 console.info(`entries: ${entries}`); 5710 kvStore.putBatch(entries).then(async () => { 5711 console.info('Succeeded in putting Batch'); 5712 if (kvStore != null) { 5713 kvStore.getEntries('batch_test_string_key').then((entries) => { 5714 console.info('Succeeded in getting Entries'); 5715 console.info(`PutBatch ${entries}`); 5716 }).catch((err: BusinessError) => { 5717 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 5718 }); 5719 } 5720 }).catch((err: BusinessError) => { 5721 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 5722 }); 5723} catch (e) { 5724 let error = e as BusinessError; 5725 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `); 5726} 5727``` 5728 5729### getEntries 5730 5731getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void 5732 5733Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. 5734> **NOTE** 5735> 5736> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 5737> For details about how to obtain **deviceId**, see [sync()](#sync). 5738 5739**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5740 5741**Parameters** 5742 5743| Name | Type | Mandatory| Description | 5744| --------- | -------------------------------------- | ---- | ---------------------------------------------- | 5745| deviceId | string | Yes | ID of the target device. | 5746| keyPrefix | string | Yes | Key prefix to match. | 5747| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| 5748 5749**Error codes** 5750 5751For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5752 5753| ID| **Error Message** | 5754| ------------ | -------------------------------------- | 5755| 15100003 | Database corrupted. | 5756| 15100005 | Database or result set already closed. | 5757 5758**Example** 5759 5760```ts 5761import { BusinessError } from '@ohos.base'; 5762 5763try { 5764 let entries: distributedKVStore.Entry[] = []; 5765 for (let i = 0; i < 10; i++) { 5766 let key = 'batch_test_string_key'; 5767 let entry: distributedKVStore.Entry = { 5768 key: key + i, 5769 value: { 5770 type: distributedKVStore.ValueType.STRING, 5771 value: 'batch_test_string_value' 5772 } 5773 } 5774 entries.push(entry); 5775 } 5776 console.info(`entries : ${entries}`); 5777 kvStore.putBatch(entries, async (err) => { 5778 if (err != undefined) { 5779 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 5780 return; 5781 } 5782 console.info('Succeeded in putting batch'); 5783 if (kvStore != null) { 5784 kvStore.getEntries('localDeviceId', 'batch_test_string_key', (err, entries) => { 5785 if (err != undefined) { 5786 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 5787 return; 5788 } 5789 console.info('Succeeded in getting entries'); 5790 console.info(`entries.length: ${entries.length}`); 5791 console.info(`entries[0]: ${entries[0]}`); 5792 }); 5793 } 5794 }); 5795} catch (e) { 5796 let error = e as BusinessError; 5797 console.error(`Failed to put batch.code is ${error.code},message is ${error.message}`); 5798} 5799``` 5800 5801### getEntries 5802 5803getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> 5804 5805Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. 5806> **NOTE** 5807> 5808> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 5809> For details about how to obtain **deviceId**, see [sync()](#sync). 5810 5811**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5812 5813**Parameters** 5814 5815| Name | Type| Mandatory| Description | 5816| --------- | -------- | ---- | ------------------------ | 5817| deviceId | string | Yes | ID of the target device.| 5818| keyPrefix | string | Yes | Key prefix to match. | 5819 5820**Return value** 5821 5822| Type | Description | 5823| -------------------------------- | ------------------------------------------------- | 5824| Promise<[Entry](#entry)[]> | Promise used to return all the KV pairs that match the given condition.| 5825 5826**Error codes** 5827 5828For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5829 5830| ID| **Error Message** | 5831| ------------ | -------------------------------------- | 5832| 15100003 | Database corrupted. | 5833| 15100005 | Database or result set already closed. | 5834 5835**Example** 5836 5837```ts 5838import { BusinessError } from '@ohos.base'; 5839 5840try { 5841 let entries: distributedKVStore.Entry[] = []; 5842 for (let i = 0; i < 10; i++) { 5843 let key = 'batch_test_string_key'; 5844 let entry: distributedKVStore.Entry = { 5845 key: key + i, 5846 value: { 5847 type: distributedKVStore.ValueType.STRING, 5848 value: 'batch_test_string_value' 5849 } 5850 } 5851 entries.push(entry); 5852 } 5853 console.info(`entries: ${entries}`); 5854 kvStore.putBatch(entries).then(async () => { 5855 console.info('Succeeded in putting batch'); 5856 if (kvStore != null) { 5857 kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { 5858 console.info('Succeeded in getting entries'); 5859 console.info(`entries.length: ${entries.length}`); 5860 console.info(`entries[0]: ${entries[0]}`); 5861 console.info(`entries[0].value: ${entries[0].value}`); 5862 console.info(`entries[0].value.value: ${entries[0].value.value}`); 5863 }).catch((err: BusinessError) => { 5864 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 5865 }); 5866 } 5867 }).catch((err: BusinessError) => { 5868 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 5869 }); 5870} catch (e) { 5871 let error = e as BusinessError; 5872 console.error(`Failed to put batch.code is ${error.code},message is ${error.message}`); 5873} 5874``` 5875 5876### getEntries 5877 5878getEntries(query: Query, callback: AsyncCallback<Entry[]>): void 5879 5880Obtains all KV pairs that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. 5881 5882**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5883 5884**Parameters** 5885 5886| Name | Type | Mandatory| Description | 5887| -------- | -------------------------------------- | ---- | ----------------------------------------------------- | 5888| query | [Query](#query) | Yes | Key prefix to match. | 5889| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs that match the specified **Query** object on the local device.| 5890 5891**Error codes** 5892 5893For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5894 5895| ID| **Error Message** | 5896| ------------ | -------------------------------------- | 5897| 15100003 | Database corrupted. | 5898| 15100005 | Database or result set already closed. | 5899 5900**Example** 5901 5902```ts 5903import { BusinessError } from '@ohos.base'; 5904 5905try { 5906 let arr = new Uint8Array([21, 31]); 5907 let entries: distributedKVStore.Entry[] = []; 5908 for (let i = 0; i < 10; i++) { 5909 let key = 'batch_test_bool_key'; 5910 let entry: distributedKVStore.Entry = { 5911 key: key + i, 5912 value: { 5913 type: distributedKVStore.ValueType.BYTE_ARRAY, 5914 value: arr 5915 } 5916 } 5917 entries.push(entry); 5918 } 5919 console.info(`entries: {entries}`); 5920 kvStore.putBatch(entries, async (err) => { 5921 console.info('Succeeded in putting Batch'); 5922 const query = new distributedKVStore.Query(); 5923 query.prefixKey("batch_test"); 5924 if (kvStore != null) { 5925 kvStore.getEntries(query, (err, entries) => { 5926 if (err != undefined) { 5927 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 5928 return; 5929 } 5930 console.info('Succeeded in getting Entries'); 5931 console.info(`entries.length: ${entries.length}`); 5932 console.info(`entries[0]: ${entries[0]}`); 5933 }); 5934 } 5935 }); 5936} catch (e) { 5937 let error = e as BusinessError; 5938 console.error(`Failed to get Entries.code is ${error.code},message is ${error.message}`); 5939} 5940``` 5941 5942### getEntries 5943 5944getEntries(query: Query): Promise<Entry[]> 5945 5946Obtains all KV pairs that match the specified **Query** object for this device. This API uses a promise to return the result. 5947 5948**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5949 5950**Parameters** 5951 5952| Name| Type | Mandatory| Description | 5953| ------ | -------------- | ---- | -------------- | 5954| query | [Query](#query) | Yes | **Query** object to match.| 5955 5956**Return value** 5957 5958| Type | Description | 5959| -------------------------------- | -------------------------------------------------------- | 5960| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified **Query** object on the local device.| 5961 5962**Error codes** 5963 5964For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 5965 5966| ID| **Error Message** | 5967| ------------ | -------------------------------------- | 5968| 15100003 | Database corrupted. | 5969| 15100005 | Database or result set already closed. | 5970 5971**Example** 5972 5973```ts 5974import { BusinessError } from '@ohos.base'; 5975 5976try { 5977 let arr = new Uint8Array([21, 31]); 5978 let entries: distributedKVStore.Entry[] = []; 5979 for (let i = 0; i < 10; i++) { 5980 let key = 'batch_test_bool_key'; 5981 let entry: distributedKVStore.Entry = { 5982 key: key + i, 5983 value: { 5984 type: distributedKVStore.ValueType.BYTE_ARRAY, 5985 value: arr 5986 } 5987 } 5988 entries.push(entry); 5989 } 5990 console.info(`entries: {entries}`); 5991 kvStore.putBatch(entries).then(async () => { 5992 console.info('Succeeded in putting Batch'); 5993 const query = new distributedKVStore.Query(); 5994 query.prefixKey("batch_test"); 5995 if (kvStore != null) { 5996 kvStore.getEntries(query).then((entries) => { 5997 console.info('Succeeded in getting Entries'); 5998 }).catch((err: BusinessError) => { 5999 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 6000 }); 6001 } 6002 }).catch((err: BusinessError) => { 6003 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`) 6004 }); 6005 console.info('Succeeded in getting Entries'); 6006} catch (e) { 6007 let error = e as BusinessError; 6008 console.error(`Failed to get Entries.code is ${error.code},message is ${error.message}`); 6009} 6010``` 6011 6012### getEntries 6013 6014getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void 6015 6016Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 6017> **NOTE** 6018> 6019> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6020> For details about how to obtain **deviceId**, see [sync()](#sync). 6021 6022**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6023 6024**Parameters** 6025 6026| Name | Type | Mandatory| Description | 6027| -------- | -------------------------------------- | ---- | ------------------------------------------------------- | 6028| deviceId | string | Yes | ID of the target device. | 6029| query | [Query](#query) | Yes | **Query** object to match. | 6030| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs that match the specified device ID and **Query** object.| 6031 6032**Error codes** 6033 6034For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6035 6036| ID| **Error Message** | 6037| ------------ | -------------------------------------- | 6038| 15100003 | Database corrupted. | 6039| 15100005 | Database or result set already closed. | 6040 6041**Example** 6042 6043```ts 6044import { BusinessError } from '@ohos.base'; 6045 6046try { 6047 let arr = new Uint8Array([21, 31]); 6048 let entries: distributedKVStore.Entry[] = []; 6049 for (let i = 0; i < 10; i++) { 6050 let key = 'batch_test_bool_key'; 6051 let entry: distributedKVStore.Entry = { 6052 key: key + i, 6053 value: { 6054 type: distributedKVStore.ValueType.BYTE_ARRAY, 6055 value: arr 6056 } 6057 } 6058 entries.push(entry); 6059 } 6060 console.info(`entries: ${entries}`); 6061 kvStore.putBatch(entries, async (err) => { 6062 if (err != undefined) { 6063 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6064 return; 6065 } 6066 console.info('Succeeded in putting batch'); 6067 let query = new distributedKVStore.Query(); 6068 query.deviceId('localDeviceId'); 6069 query.prefixKey("batch_test"); 6070 if (kvStore != null) { 6071 kvStore.getEntries('localDeviceId', query, (err, entries) => { 6072 if (err != undefined) { 6073 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 6074 return; 6075 } 6076 console.info('Succeeded in getting entries'); 6077 console.info(`entries.length: ${entries.length}`); 6078 console.info(`entries[0]: ${entries[0]}`); 6079 }) 6080 } 6081 }); 6082 console.info('Succeeded in getting entries'); 6083} catch (e) { 6084 let error = e as BusinessError; 6085 console.error(`Failed to get entries.code is ${error.code},message is ${error.message}`); 6086} 6087``` 6088 6089### getEntries 6090 6091getEntries(deviceId: string, query: Query): Promise<Entry[]> 6092 6093Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. 6094> **NOTE** 6095> 6096> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6097> For details about how to obtain **deviceId**, see [sync()](#sync). 6098 6099**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6100 6101**Parameters** 6102 6103| Name | Type | Mandatory| Description | 6104| -------- | -------------- | ---- | -------------------- | 6105| deviceId | string | Yes | ID of the target device.| 6106| query | [Query](#query) | Yes | **Query** object to match. | 6107 6108**Return value** 6109 6110| Type | Description | 6111| -------------------------------- | ---------------------------------------------------------- | 6112| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified device ID and **Query** object.| 6113 6114**Error codes** 6115 6116For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6117 6118| ID| **Error Message** | 6119| ------------ | -------------------------------------- | 6120| 15100003 | Database corrupted. | 6121| 15100005 | Database or result set already closed. | 6122 6123**Example** 6124 6125```ts 6126import { BusinessError } from '@ohos.base'; 6127 6128try { 6129 let arr = new Uint8Array([21, 31]); 6130 let entries: distributedKVStore.Entry[] = []; 6131 for (let i = 0; i < 10; i++) { 6132 let key = 'batch_test_bool_key'; 6133 let entry: distributedKVStore.Entry = { 6134 key: key + i, 6135 value: { 6136 type: distributedKVStore.ValueType.BYTE_ARRAY, 6137 value: arr 6138 } 6139 } 6140 entries.push(entry); 6141 } 6142 console.info(`entries: ${entries}`); 6143 kvStore.putBatch(entries).then(async () => { 6144 console.info('Succeeded in putting batch'); 6145 let query = new distributedKVStore.Query(); 6146 query.deviceId('localDeviceId'); 6147 query.prefixKey("batch_test"); 6148 if (kvStore != null) { 6149 kvStore.getEntries('localDeviceId', query).then((entries) => { 6150 console.info('Succeeded in getting entries'); 6151 }).catch((err: BusinessError) => { 6152 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 6153 }); 6154 } 6155 }).catch((err: BusinessError) => { 6156 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6157 }); 6158 console.info('Succeeded in getting entries'); 6159} catch (e) { 6160 let error = e as BusinessError; 6161 console.error(`Failed to get entries.code is ${error.code},message is ${error.message}`); 6162} 6163``` 6164 6165### getResultSet 6166 6167getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void 6168 6169Obtains a result set with the specified prefix for this device. This API uses an asynchronous callback to return the result. 6170 6171**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6172 6173**Parameters** 6174 6175| Name | Type | Mandatory| Description | 6176| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | 6177| keyPrefix | string | Yes | Key prefix to match. | 6178| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the result set with the specified prefix.| 6179 6180**Error codes** 6181 6182For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6183 6184| ID| **Error Message** | 6185| ------------ | -------------------------------------- | 6186| 15100001 | Over max limits. | 6187| 15100003 | Database corrupted. | 6188| 15100005 | Database or result set already closed. | 6189 6190**Example** 6191 6192```ts 6193import { BusinessError } from '@ohos.base'; 6194 6195try { 6196 let resultSet: distributedKVStore.KVStoreResultSet; 6197 let entries: distributedKVStore.Entry[] = []; 6198 for (let i = 0; i < 10; i++) { 6199 let key = 'batch_test_string_key'; 6200 let entry: distributedKVStore.Entry = { 6201 key: key + i, 6202 value: { 6203 type: distributedKVStore.ValueType.STRING, 6204 value: 'batch_test_string_value' 6205 } 6206 } 6207 entries.push(entry); 6208 } 6209 kvStore.putBatch(entries, async (err) => { 6210 if (err != undefined) { 6211 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6212 return; 6213 } 6214 console.info('Succeeded in putting batch'); 6215 if (kvStore != null) { 6216 kvStore.getResultSet('batch_test_string_key', async (err, result) => { 6217 if (err != undefined) { 6218 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6219 return; 6220 } 6221 console.info('Succeeded in getting result set'); 6222 resultSet = result; 6223 if (kvStore != null) { 6224 kvStore.closeResultSet(resultSet, (err) => { 6225 if (err != undefined) { 6226 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 6227 return; 6228 } 6229 console.info('Succeeded in closing result set'); 6230 }) 6231 } 6232 }); 6233 } 6234 }); 6235} catch (e) { 6236 let error = e as BusinessError; 6237 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 6238} 6239``` 6240 6241### getResultSet 6242 6243getResultSet(keyPrefix: string): Promise<KVStoreResultSet> 6244 6245Obtains a result set with the specified prefix for this device. This API uses a promise to return the result. 6246 6247**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6248 6249**Parameters** 6250 6251| Name | Type | Mandatory| Description | 6252| --------- | ------ | ---- | -------------------- | 6253| keyPrefix | string | Yes | Key prefix to match.| 6254 6255**Return value** 6256 6257| Type | Description | 6258| ---------------------------------------------------- | --------------------------------------- | 6259| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the result set with the specified prefix.| 6260 6261**Error codes** 6262 6263For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6264 6265| ID| **Error Message** | 6266| ------------ | -------------------------------------- | 6267| 15100001 | Over max limits. | 6268| 15100003 | Database corrupted. | 6269| 15100005 | Database or result set already closed. | 6270 6271**Example** 6272 6273```ts 6274import { BusinessError } from '@ohos.base'; 6275 6276try { 6277 let resultSet: distributedKVStore.KVStoreResultSet; 6278 let entries: distributedKVStore.Entry[] = []; 6279 for (let i = 0; i < 10; i++) { 6280 let key = 'batch_test_string_key'; 6281 let entry: distributedKVStore.Entry = { 6282 key: key + i, 6283 value: { 6284 type: distributedKVStore.ValueType.STRING, 6285 value: 'batch_test_string_value' 6286 } 6287 } 6288 entries.push(entry); 6289 } 6290 kvStore.putBatch(entries).then(async () => { 6291 console.info('Succeeded in putting batch'); 6292 }).catch((err: BusinessError) => { 6293 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6294 }); 6295 kvStore.getResultSet('batch_test_string_key').then((result) => { 6296 console.info('Succeeded in getting result set'); 6297 resultSet = result; 6298 if (kvStore != null) { 6299 kvStore.closeResultSet(resultSet).then(() => { 6300 console.info('Succeeded in closing result set'); 6301 }).catch((err: BusinessError) => { 6302 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 6303 }); 6304 } 6305 }).catch((err: BusinessError) => { 6306 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6307 }); 6308} catch (e) { 6309 let error = e as BusinessError; 6310 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 6311} 6312``` 6313 6314### getResultSet 6315 6316getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void 6317 6318Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. 6319> **NOTE** 6320> 6321> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6322> For details about how to obtain **deviceId**, see [sync()](#sync). 6323 6324**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6325 6326**Parameters** 6327 6328| Name | Type | Mandatory| Description | 6329| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 6330| deviceId | string | Yes | ID of the target device. | 6331| keyPrefix | string | Yes | Key prefix to match. | 6332| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object that matches the specified device ID and key prefix.| 6333 6334**Error codes** 6335 6336For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6337 6338| ID| **Error Message** | 6339| ------------ | -------------------------------------- | 6340| 15100001 | Over max limits. | 6341| 15100003 | Database corrupted. | 6342| 15100005 | Database or result set already closed. | 6343 6344**Example** 6345 6346```ts 6347import { BusinessError } from '@ohos.base'; 6348 6349try { 6350 let resultSet: distributedKVStore.KVStoreResultSet; 6351 kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async (err, result) => { 6352 if (err != undefined) { 6353 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6354 return; 6355 } 6356 console.info('Succeeded in getting resultSet'); 6357 resultSet = result; 6358 if (kvStore != null) { 6359 kvStore.closeResultSet(resultSet, (err) => { 6360 if (err != undefined) { 6361 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6362 return; 6363 } 6364 console.info('Succeeded in closing resultSet'); 6365 }) 6366 } 6367 }); 6368} catch (e) { 6369 let error = e as BusinessError; 6370 console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`); 6371} 6372``` 6373 6374### getResultSet 6375 6376getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet> 6377 6378Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. 6379> **NOTE** 6380> 6381> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6382> For details about how to obtain **deviceId**, see [sync()](#sync). 6383 6384**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6385 6386**Parameters** 6387 6388| Name | Type| Mandatory| Description | 6389| --------- | -------- | ---- | ------------------------ | 6390| deviceId | string | Yes | ID of the target device.| 6391| keyPrefix | string | Yes | Key prefix to match. | 6392 6393**Return value** 6394 6395| Type | Description | 6396| ------------------------------------------------------ | ------------------------------------------------------------ | 6397| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object that matches the specified device ID and key prefix.| 6398 6399**Error codes** 6400 6401For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6402 6403| ID| **Error Message** | 6404| ------------ | -------------------------------------- | 6405| 15100001 | Over max limits. | 6406| 15100003 | Database corrupted. | 6407| 15100005 | Database or result set already closed. | 6408 6409**Example** 6410 6411```ts 6412import { BusinessError } from '@ohos.base'; 6413 6414try { 6415 let resultSet: distributedKVStore.KVStoreResultSet; 6416 kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { 6417 console.info('Succeeded in getting resultSet'); 6418 resultSet = result; 6419 if (kvStore != null) { 6420 kvStore.closeResultSet(resultSet).then(() => { 6421 console.info('Succeeded in closing resultSet'); 6422 }).catch((err: BusinessError) => { 6423 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6424 }); 6425 } 6426 }).catch((err: BusinessError) => { 6427 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6428 }); 6429} catch (e) { 6430 let error = e as BusinessError; 6431 console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`); 6432} 6433``` 6434 6435### getResultSet 6436 6437getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreResultSet>): void 6438 6439Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 6440> **NOTE** 6441> 6442> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6443> For details about how to obtain **deviceId**, see [sync()](#sync). 6444 6445**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6446 6447**Parameters** 6448 6449| Name | Type | Mandatory| Description | 6450| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 6451| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | 6452| query | [Query](#query) | Yes | **Query** object to match. | 6453| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object that matches the specified device ID and **Query** object.| 6454 6455**Error codes** 6456 6457For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6458 6459| ID| **Error Message** | 6460| ------------ | -------------------------------------- | 6461| 15100001 | Over max limits. | 6462| 15100003 | Database corrupted. | 6463| 15100005 | Database or result set already closed. | 6464 6465**Example** 6466 6467```ts 6468import { BusinessError } from '@ohos.base'; 6469 6470try { 6471 let resultSet: distributedKVStore.KVStoreResultSet; 6472 let entries: distributedKVStore.Entry[] = []; 6473 for (let i = 0; i < 10; i++) { 6474 let key = 'batch_test_string_key'; 6475 let entry: distributedKVStore.Entry = { 6476 key: key + i, 6477 value: { 6478 type: distributedKVStore.ValueType.STRING, 6479 value: 'batch_test_string_value' 6480 } 6481 } 6482 entries.push(entry); 6483 } 6484 kvStore.putBatch(entries, async (err) => { 6485 if (err != undefined) { 6486 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6487 return; 6488 } 6489 console.info('Succeeded in putting batch'); 6490 const query = new distributedKVStore.Query(); 6491 query.prefixKey("batch_test"); 6492 if (kvStore != null) { 6493 kvStore.getResultSet('localDeviceId', query, async (err, result) => { 6494 if (err != undefined) { 6495 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6496 return; 6497 } 6498 console.info('Succeeded in getting resultSet'); 6499 resultSet = result; 6500 if (kvStore != null) { 6501 kvStore.closeResultSet(resultSet, (err) => { 6502 if (err != undefined) { 6503 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6504 return; 6505 } 6506 console.info('Succeeded in closing resultSet'); 6507 }) 6508 } 6509 }); 6510 } 6511 }); 6512} catch (e) { 6513 let error = e as BusinessError; 6514 console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`); 6515} 6516``` 6517 6518### getResultSet 6519 6520getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> 6521 6522Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. 6523> **NOTE** 6524> 6525> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6526> For details about how to obtain **deviceId**, see [sync()](#sync). 6527 6528**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6529 6530**Parameters** 6531 6532| Name | Type | Mandatory| Description | 6533| -------- | -------------- | ---- | ---------------------------------- | 6534| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| 6535| query | [Query](#query) | Yes | **Query** object to match. | 6536 6537**Return value** 6538 6539| Type | Description | 6540| ------------------------------------------------------ | ------------------------------------------------------------ | 6541| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object that matches the specified device ID and **Query** object.| 6542 6543**Error codes** 6544 6545For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6546 6547| ID| **Error Message** | 6548| ------------ | -------------------------------------- | 6549| 15100001 | Over max limits. | 6550| 15100003 | Database corrupted. | 6551| 15100005 | Database or result set already closed. | 6552 6553**Example** 6554 6555```ts 6556import { BusinessError } from '@ohos.base'; 6557 6558try { 6559 let resultSet: distributedKVStore.KVStoreResultSet; 6560 let entries: distributedKVStore.Entry[] = []; 6561 for (let i = 0; i < 10; i++) { 6562 let key = 'batch_test_string_key'; 6563 let entry: distributedKVStore.Entry = { 6564 key: key + i, 6565 value: { 6566 type: distributedKVStore.ValueType.STRING, 6567 value: 'batch_test_string_value' 6568 } 6569 } 6570 entries.push(entry); 6571 } 6572 kvStore.putBatch(entries).then(async () => { 6573 console.info('Succeeded in putting batch'); 6574 }).catch((err: BusinessError) => { 6575 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6576 }); 6577 const query = new distributedKVStore.Query(); 6578 query.prefixKey("batch_test"); 6579 if (kvStore != null) { 6580 kvStore.getResultSet('localDeviceId', query).then((result) => { 6581 console.info('Succeeded in getting resultSet'); 6582 resultSet = result; 6583 if (kvStore != null) { 6584 kvStore.closeResultSet(resultSet).then(() => { 6585 console.info('Succeeded in closing resultSet'); 6586 }).catch((err: BusinessError) => { 6587 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6588 }); 6589 } 6590 }).catch((err: BusinessError) => { 6591 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6592 }); 6593 } 6594 query.deviceId('localDeviceId'); 6595 console.info("GetResultSet " + query.getSqlLike()); 6596 6597} catch (e) { 6598 let error = e as BusinessError; 6599 console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`); 6600} 6601``` 6602 6603### getResultSet 6604 6605getResultSet(query: Query): Promise<KVStoreResultSet> 6606 6607Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses a promise to return the result. 6608 6609**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6610 6611**Parameters** 6612 6613| Name| Type | Mandatory| Description | 6614| ------ | -------------- | ---- | -------------- | 6615| query | [Query](#query) | Yes | **Query** object to match.| 6616 6617**Return value** 6618 6619| Type | Description | 6620| ---------------------------------------------------- | ------------------------------------------------------------ | 6621| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| 6622 6623**Error codes** 6624 6625For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6626 6627| ID| **Error Message** | 6628| ------------ | -------------------------------------- | 6629| 15100001 | Over max limits. | 6630| 15100003 | Database corrupted. | 6631| 15100005 | Database or result set already closed. | 6632 6633**Example** 6634 6635```ts 6636import { BusinessError } from '@ohos.base'; 6637 6638try { 6639 let resultSet: distributedKVStore.KVStoreResultSet; 6640 let entries: distributedKVStore.Entry[] = []; 6641 for (let i = 0; i < 10; i++) { 6642 let key = 'batch_test_string_key'; 6643 let entry: distributedKVStore.Entry = { 6644 key: key + i, 6645 value: { 6646 type: distributedKVStore.ValueType.STRING, 6647 value: 'batch_test_string_value' 6648 } 6649 } 6650 entries.push(entry); 6651 } 6652 kvStore.putBatch(entries).then(async () => { 6653 console.info('Succeeded in putting batch'); 6654 }).catch((err: BusinessError) => { 6655 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6656 }); 6657 const query = new distributedKVStore.Query(); 6658 query.prefixKey("batch_test"); 6659 kvStore.getResultSet(query).then((result) => { 6660 console.info('Succeeded in getting result set'); 6661 resultSet = result; 6662 }).catch((err: BusinessError) => { 6663 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6664 }); 6665} catch (e) { 6666 let error = e as BusinessError; 6667 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 6668} 6669``` 6670 6671### getResultSet 6672 6673getResultSet(query: Query, callback:AsyncCallback<KVStoreResultSet>): void 6674 6675Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses an asynchronous callback to return the result. 6676> **NOTE** 6677> 6678> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6679> For details about how to obtain **deviceId**, see [sync()](#sync). 6680 6681**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6682 6683**Parameters** 6684 6685| Name | Type | Mandatory| Description | 6686| -------- | -------------- | ---- | ---------------------------------- | 6687| query | [Query](#query) | Yes | **Query** object to match. | 6688| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained. | 6689 6690 6691**Error codes** 6692 6693For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6694 6695| ID| **Error Message** | 6696| ------------ | -------------------------------------- | 6697| 15100001 | Over max limits. | 6698| 15100003 | Database corrupted. | 6699| 15100005 | Database or result set already closed. | 6700 6701**Example** 6702 6703```ts 6704import { BusinessError } from '@ohos.base'; 6705 6706try { 6707 let resultSet: distributedKVStore.KVStoreResultSet; 6708 let entries: distributedKVStore.Entry[] = []; 6709 for (let i = 0; i < 10; i++) { 6710 let key = 'batch_test_string_key'; 6711 let entry: distributedKVStore.Entry = { 6712 key: key + i, 6713 value: { 6714 type: distributedKVStore.ValueType.STRING, 6715 value: 'batch_test_string_value' 6716 } 6717 } 6718 entries.push(entry); 6719 } 6720 kvStore.putBatch(entries, async (err) => { 6721 if (err != undefined) { 6722 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6723 return; 6724 } 6725 console.info('Succeeded in putting batch'); 6726 const query = new distributedKVStore.Query(); 6727 query.prefixKey("batch_test"); 6728 if (kvStore != null) { 6729 kvStore.getResultSet(query, async (err, result) => { 6730 if (err != undefined) { 6731 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6732 return; 6733 } 6734 console.info('Succeeded in getting resultSet'); 6735 resultSet = result; 6736 if (kvStore != null) { 6737 kvStore.closeResultSet(resultSet, (err) => { 6738 if (err != undefined) { 6739 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6740 return; 6741 } 6742 console.info('Succeeded in closing resultSet'); 6743 }) 6744 } 6745 }); 6746 } 6747 }); 6748} catch (e) { 6749 let error = e as BusinessError; 6750 console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`); 6751} 6752``` 6753 6754### getResultSet 6755 6756getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void 6757 6758Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses an asynchronous callback to return the result. 6759 6760**Model restriction**: This API can be used only in the stage model. 6761 6762**System API**: This is a system API. 6763 6764**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 6765 6766**Parameters** 6767 6768| Name | Type | Mandatory| Description | 6769| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 6770| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | 6771| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| 6772 6773**Error codes** 6774 6775For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6776 6777| ID| **Error Message** | 6778| ------------ | -------------------------------------- | 6779| 15100001 | Over max limits. | 6780| 15100003 | Database corrupted. | 6781| 15100005 | Database or result set already closed. | 6782 6783**Example** 6784 6785```ts 6786import dataSharePredicates from '@ohos.data.dataSharePredicates'; 6787import { BusinessError } from '@ohos.base'; 6788 6789try { 6790 let resultSet: distributedKVStore.KVStoreResultSet; 6791 let predicates = new dataSharePredicates.DataSharePredicates(); 6792 predicates.prefixKey("batch_test_string_key"); 6793 kvStore.getResultSet(predicates, async (err, result) => { 6794 if (err != undefined) { 6795 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6796 return; 6797 } 6798 console.info('Succeeded in getting result set'); 6799 resultSet = result; 6800 if (kvStore != null) { 6801 kvStore.closeResultSet(resultSet, (err) => { 6802 if (err != undefined) { 6803 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 6804 return; 6805 } 6806 console.info('Succeeded in closing result set'); 6807 }) 6808 } 6809 }); 6810} catch (e) { 6811 let error = e as BusinessError; 6812 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 6813} 6814``` 6815 6816### getResultSet 6817 6818getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> 6819 6820Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses a promise to return the result. 6821 6822**Model restriction**: This API can be used only in the stage model. 6823 6824**System API**: This is a system API. 6825 6826**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 6827 6828**Parameters** 6829 6830| Name | Type | Mandatory| Description | 6831| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | 6832| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| 6833 6834**Return value** 6835 6836| Type | Description | 6837| ---------------------------------------------------- | ------------------------- | 6838| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| 6839 6840**Error codes** 6841 6842For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6843 6844| ID| **Error Message** | 6845| ------------ | -------------------------------------- | 6846| 15100001 | Over max limits. | 6847| 15100003 | Database corrupted. | 6848| 15100005 | Database or result set already closed. | 6849 6850**Example** 6851 6852```ts 6853import dataSharePredicates from '@ohos.data.dataSharePredicates'; 6854import { BusinessError } from '@ohos.base'; 6855 6856try { 6857 let resultSet: distributedKVStore.KVStoreResultSet; 6858 let predicates = new dataSharePredicates.DataSharePredicates(); 6859 predicates.prefixKey("batch_test_string_key"); 6860 kvStore.getResultSet(predicates).then((result) => { 6861 console.info('Succeeded in getting result set'); 6862 resultSet = result; 6863 if (kvStore != null) { 6864 kvStore.closeResultSet(resultSet).then(() => { 6865 console.info('Succeeded in closing result set'); 6866 }).catch((err: BusinessError) => { 6867 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 6868 }); 6869 } 6870 }).catch((err: BusinessError) => { 6871 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6872 }); 6873} catch (e) { 6874 let error = e as BusinessError; 6875 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 6876} 6877``` 6878 6879### getResultSet 6880 6881getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void 6882 6883Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result. 6884> **NOTE** 6885> 6886> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6887> For details about how to obtain **deviceId**, see [sync()](#sync). 6888 6889**Model restriction**: This API can be used only in the stage model. 6890 6891**System API**: This is a system API. 6892 6893**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 6894 6895**Parameters** 6896 6897| Name | Type | Mandatory| Description | 6898| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 6899| deviceId | string | Yes | ID of the target device. | 6900| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | 6901| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| 6902 6903**Error codes** 6904 6905For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6906 6907| ID| **Error Message** | 6908| ------------ | -------------------------------------- | 6909| 15100001 | Over max limits. | 6910| 15100003 | Database corrupted. | 6911| 15100005 | Database or result set already closed. | 6912 6913**Example** 6914 6915```ts 6916import dataSharePredicates from '@ohos.data.dataSharePredicates'; 6917import { BusinessError } from '@ohos.base'; 6918 6919try { 6920 let resultSet: distributedKVStore.KVStoreResultSet; 6921 let predicates = new dataSharePredicates.DataSharePredicates(); 6922 predicates.prefixKey("batch_test_string_key"); 6923 kvStore.getResultSet('localDeviceId', predicates, async (err, result) => { 6924 if (err != undefined) { 6925 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6926 return; 6927 } 6928 console.info('Succeeded in getting result set'); 6929 resultSet = result; 6930 if (kvStore != null) { 6931 kvStore.closeResultSet(resultSet, (err) => { 6932 if (err != undefined) { 6933 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 6934 return; 6935 } 6936 console.info('Succeeded in closing result set'); 6937 }) 6938 } 6939 }); 6940} catch (e) { 6941 let error = e as BusinessError; 6942 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 6943} 6944``` 6945 6946### getResultSet 6947 6948getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> 6949 6950Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result. 6951> **NOTE** 6952> 6953> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6954> For details about how to obtain **deviceId**, see [sync()](#sync). 6955 6956**Model restriction**: This API can be used only in the stage model. 6957 6958**System API**: This is a system API. 6959 6960**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider 6961 6962**Parameters** 6963 6964| Name | Type | Mandatory| Description | 6965| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | 6966| deviceId | string | Yes | ID of the target device. | 6967| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| 6968 6969**Return value** 6970 6971| Type | Description | 6972| ---------------------------------------------------- | ------------------------- | 6973| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| 6974 6975**Error codes** 6976 6977For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 6978 6979| ID| **Error Message** | 6980| ------------ | -------------------------------------- | 6981| 15100001 | Over max limits. | 6982| 15100003 | Database corrupted. | 6983| 15100005 | Database or result set already closed. | 6984 6985**Example** 6986 6987```ts 6988import dataSharePredicates from '@ohos.data.dataSharePredicates'; 6989import { BusinessError } from '@ohos.base'; 6990 6991try { 6992 let resultSet: distributedKVStore.KVStoreResultSet; 6993 let predicates = new dataSharePredicates.DataSharePredicates(); 6994 predicates.prefixKey("batch_test_string_key"); 6995 kvStore.getResultSet('localDeviceId', predicates).then((result) => { 6996 console.info('Succeeded in getting result set'); 6997 resultSet = result; 6998 if (kvStore != null) { 6999 kvStore.closeResultSet(resultSet).then(() => { 7000 console.info('Succeeded in closing result set'); 7001 }).catch((err: BusinessError) => { 7002 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 7003 }); 7004 } 7005 }).catch((err: BusinessError) => { 7006 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 7007 }); 7008} catch (e) { 7009 let error = e as BusinessError; 7010 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 7011} 7012``` 7013 7014### getResultSize 7015 7016getResultSize(query: Query, callback: AsyncCallback<number>): void 7017 7018Obtains the number of results that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. 7019 7020**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 7021 7022**Parameters** 7023 7024| Name | Type | Mandatory| Description | 7025| -------- | --------------------------- | ---- | ------------------------------------------------- | 7026| query | [Query](#query) | Yes | **Query** object to match. | 7027| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| 7028 7029**Error codes** 7030 7031For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 7032 7033| ID| **Error Message** | 7034| ------------ | -------------------------------------- | 7035| 15100003 | Database corrupted. | 7036| 15100005 | Database or result set already closed. | 7037 7038**Example** 7039 7040```ts 7041import { BusinessError } from '@ohos.base'; 7042 7043try { 7044 let entries: distributedKVStore.Entry[] = []; 7045 for (let i = 0; i < 10; i++) { 7046 let key = 'batch_test_string_key'; 7047 let entry: distributedKVStore.Entry = { 7048 key: key + i, 7049 value: { 7050 type: distributedKVStore.ValueType.STRING, 7051 value: 'batch_test_string_value' 7052 } 7053 } 7054 entries.push(entry); 7055 } 7056 kvStore.putBatch(entries, async (err) => { 7057 console.info('Succeeded in putting batch'); 7058 const query = new distributedKVStore.Query(); 7059 query.prefixKey("batch_test"); 7060 if (kvStore != null) { 7061 kvStore.getResultSize(query, async (err, resultSize) => { 7062 if (err != undefined) { 7063 console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); 7064 return; 7065 } 7066 console.info('Succeeded in getting result set size'); 7067 }); 7068 } 7069 }); 7070} catch (e) { 7071 let error = e as BusinessError; 7072 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 7073} 7074``` 7075 7076### getResultSize 7077 7078getResultSize(query: Query): Promise<number> 7079 7080Obtains the number of results that match the specified **Query** object for this device. This API uses a promise to return the result. 7081 7082**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 7083 7084**Parameters** 7085 7086| Name| Type | Mandatory| Description | 7087| ------ | -------------- | ---- | -------------- | 7088| query | [Query](#query) | Yes | **Query** object to match.| 7089 7090**Return value** 7091 7092| Type | Description | 7093| --------------------- | ---------------------------------------------------- | 7094| Promise<number> | Promise used to return the number of results obtained.| 7095 7096**Error codes** 7097 7098For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 7099 7100| ID| **Error Message** | 7101| ------------ | -------------------------------------- | 7102| 15100003 | Database corrupted. | 7103| 15100005 | Database or result set already closed. | 7104 7105**Example** 7106 7107```ts 7108import { BusinessError } from '@ohos.base'; 7109 7110try { 7111 let entries: distributedKVStore.Entry[] = []; 7112 for (let i = 0; i < 10; i++) { 7113 let key = 'batch_test_string_key'; 7114 let entry: distributedKVStore.Entry = { 7115 key: key + i, 7116 value: { 7117 type: distributedKVStore.ValueType.STRING, 7118 value: 'batch_test_string_value' 7119 } 7120 } 7121 entries.push(entry); 7122 } 7123 kvStore.putBatch(entries).then(async () => { 7124 console.info('Succeeded in putting batch'); 7125 }).catch((err: BusinessError) => { 7126 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 7127 }); 7128 const query = new distributedKVStore.Query(); 7129 query.prefixKey("batch_test"); 7130 kvStore.getResultSize(query).then((resultSize) => { 7131 console.info('Succeeded in getting result set size'); 7132 }).catch((err: BusinessError) => { 7133 console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); 7134 }); 7135} catch (e) { 7136 let error = e as BusinessError; 7137 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 7138} 7139``` 7140 7141### getResultSize 7142 7143getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; 7144 7145Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 7146> **NOTE** 7147> 7148> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 7149> For details about how to obtain **deviceId**, see [sync()](#sync). 7150 7151**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 7152 7153**Parameters** 7154 7155| Name | Type | Mandatory| Description | 7156| -------- | --------------------------- | ---- | --------------------------------------------------- | 7157| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | 7158| query | [Query](#query) | Yes | **Query** object to match. | 7159| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained. | 7160 7161**Error codes** 7162 7163For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 7164 7165| ID| **Error Message** | 7166| ------------ | -------------------------------------- | 7167| 15100003 | Database corrupted. | 7168| 15100005 | Database or result set already closed. | 7169 7170**Example** 7171 7172```ts 7173import { BusinessError } from '@ohos.base'; 7174 7175try { 7176 let entries: distributedKVStore.Entry[] = []; 7177 for (let i = 0; i < 10; i++) { 7178 let key = 'batch_test_string_key'; 7179 let entry: distributedKVStore.Entry = { 7180 key: key + i, 7181 value: { 7182 type: distributedKVStore.ValueType.STRING, 7183 value: 'batch_test_string_value' 7184 } 7185 } 7186 entries.push(entry); 7187 } 7188 kvStore.putBatch(entries, async (err) => { 7189 if (err != undefined) { 7190 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 7191 return; 7192 } 7193 console.info('Succeeded in putting batch'); 7194 const query = new distributedKVStore.Query(); 7195 query.prefixKey("batch_test"); 7196 if (kvStore != null) { 7197 kvStore.getResultSize('localDeviceId', query, async (err, resultSize) => { 7198 if (err != undefined) { 7199 console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`); 7200 return; 7201 } 7202 console.info('Succeeded in getting resultSize'); 7203 }); 7204 } 7205 }); 7206} catch (e) { 7207 let error = e as BusinessError; 7208 console.error(`Failed to get resultSize.code is ${error.code},message is ${error.message}`); 7209} 7210``` 7211 7212### getResultSize 7213 7214getResultSize(deviceId: string, query: Query): Promise<number> 7215 7216Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. 7217> **NOTE** 7218> 7219> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 7220> For details about how to obtain **deviceId**, see [sync()](#sync). 7221 7222**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 7223 7224**Parameters** 7225 7226| Name | Type | Mandatory| Description | 7227| -------- | -------------- | ---- | ---------------------------------- | 7228| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| 7229| query | [Query](#query) | Yes | **Query** object to match. | 7230 7231**Return value** 7232 7233| Type | Description | 7234| --------------------- | ------------------------------------------------------ | 7235| Promise<number> | Promise used to return the number of results obtained. | 7236 7237**Error codes** 7238 7239For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). 7240 7241| ID| **Error Message** | 7242| ------------ | -------------------------------------- | 7243| 15100003 | Database corrupted. | 7244| 15100005 | Database or result set already closed. | 7245 7246**Example** 7247 7248```ts 7249import { BusinessError } from '@ohos.base'; 7250 7251try { 7252 let entries: distributedKVStore.Entry[] = []; 7253 for (let i = 0; i < 10; i++) { 7254 let key = 'batch_test_string_key'; 7255 let entry: distributedKVStore.Entry = { 7256 key: key + i, 7257 value: { 7258 type: distributedKVStore.ValueType.STRING, 7259 value: 'batch_test_string_value' 7260 } 7261 } 7262 entries.push(entry); 7263 } 7264 kvStore.putBatch(entries).then(async () => { 7265 console.info('Succeeded in putting batch'); 7266 }).catch((err: BusinessError) => { 7267 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 7268 }); 7269 let query = new distributedKVStore.Query(); 7270 query.prefixKey("batch_test"); 7271 kvStore.getResultSize('localDeviceId', query).then((resultSize) => { 7272 console.info('Succeeded in getting resultSize'); 7273 }).catch((err: BusinessError) => { 7274 console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`); 7275 }); 7276} catch (e) { 7277 let error = e as BusinessError; 7278 console.error(`Failed to get resultSize.code is ${error.code},message is ${error.message}`); 7279} 7280``` 7281