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