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, and querying data, and synchronizing data across devices. 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 data in single KV stores and synchronizing data across devices. The single KV stores manage data without distinguishing devices. 11- [DeviceKVStore](#devicekvstore): provides APIs for querying data in device KV stores and synchronizing data across devices. 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 | Type | Read Only| Optional| Description | 41| --------------------- | ------ | ---- | ---- | ---------------------------------------------------------- | 42| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key in the database, which is 1024 bytes. | 43| MAX_VALUE_LENGTH | number | Yes | No | Maximum length of a value in the database, which is 4194303 bytes. | 44| MAX_KEY_LENGTH_DEVICE | number | Yes | No | Maximum length of a key in a device KV store, which is 896 bytes.| 45| MAX_STORE_ID_LENGTH | number | Yes | No | Maximum length of a KV store ID, which is 128 bytes. | 46| MAX_QUERY_LENGTH | number | Yes | No | Maximum query length, which is 512000 bytes. | 47| MAX_BATCH_SIZE | number | Yes | No | Maximum number of batch operations allowed, which is 128. | 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 | Value| Description | 56| ---------- | - | -------------------- | 57| STRING | 0 | String. | 58| INTEGER | 1 | Integer. | 59| FLOAT | 2 | Float (single-precision floating point). | 60| BYTE_ARRAY | 3 | Byte array.| 61| BOOLEAN | 4 | Boolean. | 62| DOUBLE | 5 | Double (double-precision floating point).| 63 64## Value 65 66Defines the **value** object in a KV store. 67 68**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 69 70| Name | Type |Mandatory | Description | 71| ----- | ------- |-----|------------------------ | 72| type | [ValueType](#valuetype) | Yes|Type of the value. | 73| value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair. | 74 75## Entry 76 77Defines the KV pairs stored in a KV store. 78 79**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 80 81| Name | Type | Mandatory| Description | 82| ----- | --------------- | ---- | -------- | 83| key | string | Yes | Key of 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 | Value| Description | 106| --------- | - | ---------------------------------------------- | 107| PULL_ONLY | 0 | Pull data from the peer end to the local end only. | 108| PUSH_ONLY | 1 | Push data from the local end to the peer end only. | 109| PUSH_PULL | 2 | 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 | Value| Description | 118| --------------------- | - | ---------------------------- | 119| SUBSCRIBE_TYPE_LOCAL | 0 | Local data changes. | 120| SUBSCRIBE_TYPE_REMOTE | 1 | Remote data changes. | 121| SUBSCRIBE_TYPE_ALL | 2 | Local and remote data changes. | 122 123## KVStoreType 124 125Enumerates the distributed KV store types. 126 127| Name | Value| Description | 128| -------------------- | - | ------------------------------------------------------------ | 129| DEVICE_COLLABORATION | 0 | 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 | 1 | 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, 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 | Value| Description | 145| -------: | - | ------------------------------------------------------------ | 146| S1 | 2 | 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 | 3 | 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 | 5 | 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 | 6 | Critical security level. Disclosure, tampering, corruption, or loss of the data may cause significant adverse impact on an individual or group.<br><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 | Read Only| Optional| Description | 172| ------- | ----------------------- | ---- | ---- | -------------------------- | 173| root | [FieldNode](#fieldnode) | No | No | Definitions of all the fields in **Value**.| 174| indexes | Array\<string> | No | No | Indexes of the fields in **Value**. Indexes are created only for **FieldNode** with this parameter specified. The format is **'$.field1'**, **'$.field2'**.| 175| mode | number | No | No | Schema mode, which can be **0** (compatible mode) or **1** (strict mode).| 176| skip | number | No | No | Number of bytes to be skipped during the value check. The value range is [0, 4 x 1024 x 1024 - 2].| 177 178Strict mode: In this mode, the value to be inserted must strictly match the schema defined, and the number and format of fields must be consistent with 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 184A constructor used to create a **Schema** instance. 185 186**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 187 188**Example** 189 190```ts 191 192let child1 = new distributedKVStore.FieldNode('id'); 193child1.type = distributedKVStore.ValueType.INTEGER; 194child1.nullable = false; 195child1.default = '1'; 196let child2 = new distributedKVStore.FieldNode('name'); 197child2.type = distributedKVStore.ValueType.STRING; 198child2.nullable = false; 199child2.default = 'zhangsan'; 200 201let schema = new distributedKVStore.Schema(); 202schema.root.appendChild(child1); 203schema.root.appendChild(child2); 204schema.indexes = ['$.id', '$.name']; 205schema.mode = 1; 206schema.skip = 0; 207``` 208 209## FieldNode 210 211Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store. 212 213**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 214 215| Name | Type | Read Only| Optional| Description | 216| -------- | ------- | ---- | ---- | ------------------------------------------------------------ | 217| nullable | boolean | No | No | Whether the field can be null. The value **true** means the node field can be null; the value **false** means the opposite.| 218| default | string | No | No | Default value of **FieldNode**. | 219| type | number | No | No | **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).| 220 221### constructor 222 223constructor(name: string) 224 225A constructor used to create a **FieldNode** instance with a string field. 226 227**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 228 229**Parameters** 230 231| Name| Type| Mandatory| Description | 232| ------ | -------- | ---- | --------------- | 233| name | string | Yes | Value of **FieldNode**, which cannot be left empty.| 234 235**Error codes** 236 237For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 238 239| ID| **Error Message** | 240| ------------ | ------------------------------------------- | 241| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Parameter verification failed. | 242 243### appendChild 244 245appendChild(child: FieldNode): boolean 246 247Appends a child node to this **FieldNode**. 248 249**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 250 251**Parameters** 252 253| Name| Type | Mandatory| Description | 254| ------ | ----------------------- | ---- | ---------------- | 255| child | [FieldNode](#fieldnode) | Yes | Child node to append.| 256 257**Return value** 258 259| Type | Description | 260| ------- | ------------------------------------------------------------ | 261| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 262 263**Error codes** 264 265For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 266 267| ID| **Error Message** | 268| ------------ | ------------------------------------------- | 269| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 270 271**Example** 272 273```ts 274 275try { 276 let node: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("root"); 277 let child1: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("child1"); 278 let child2: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("child2"); 279 let child3: distributedKVStore.FieldNode | null = new distributedKVStore.FieldNode("child3"); 280 node.appendChild(child1); 281 node.appendChild(child2); 282 node.appendChild(child3); 283 console.info("appendNode " + JSON.stringify(node)); 284 child1 = null; 285 child2 = null; 286 child3 = null; 287 node = null; 288} catch (e) { 289 console.error("AppendChild " + e); 290} 291``` 292 293## distributedKVStore.createKVManager 294 295createKVManager(config: KVManagerConfig): KVManager 296 297Creates a **KVManager** instance for KV store management. 298 299**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 300 301**Parameters** 302 303| Name| Type | Mandatory| Description | 304| ------ | ----------------------------- | ---- | --------------------------------------------------------- | 305| config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** instance, including the bundle name (cannot be empty) of the caller and user information.| 306 307**Return value** 308 309| Type | Description | 310| -------------------------------------- | ------------------------------------------ | 311| [KVManager](#kvmanager) | **KVManager** instance created.| 312 313**Error codes** 314 315For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 316 317| ID| **Error Message** | 318| ------------ | ------------------------------------------- | 319| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 320 321**Example** 322 323Stage model: 324 325```ts 326import { UIAbility } from '@kit.AbilityKit'; 327import { BusinessError } from '@kit.BasicServicesKit'; 328 329let kvManager: distributedKVStore.KVManager; 330 331export default class EntryAbility extends UIAbility { 332 onCreate() { 333 console.info("MyAbilityStage onCreate"); 334 let context = this.context; 335 const kvManagerConfig: distributedKVStore.KVManagerConfig = { 336 context: context, 337 bundleName: 'com.example.datamanagertest' 338 } 339 try { 340 kvManager = distributedKVStore.createKVManager(kvManagerConfig); 341 console.info("Succeeded in creating KVManager"); 342 } catch (e) { 343 let error = e as BusinessError; 344 console.error(`Failed to create KVManager.code is ${error.code},message is ${error.message}`); 345 } 346 if (kvManager !== undefined) { 347 kvManager = kvManager as distributedKVStore.KVManager; 348 // Perform subsequent operations such as creating a KV store. 349 // ... 350 } 351 } 352} 353``` 354 355FA model: 356 357<!--code_no_check_fa--> 358```ts 359import { featureAbility } from '@kit.AbilityKit'; 360import { BusinessError } from '@kit.BasicServicesKit'; 361 362let kvManager: distributedKVStore.KVManager; 363let context = featureAbility.getContext(); 364const kvManagerConfig: distributedKVStore.KVManagerConfig = { 365 context: context, 366 bundleName: 'com.example.datamanagertest' 367} 368try { 369 kvManager = distributedKVStore.createKVManager(kvManagerConfig); 370 console.info("Succeeded in creating KVManager"); 371} catch (e) { 372 let error = e as BusinessError; 373 console.error(`Failed to create KVManager.code is ${error.code},message is ${error.message}`); 374} 375if (kvManager !== undefined) { 376 kvManager = kvManager as distributedKVStore.KVManager; 377 // Perform subsequent operations such as creating a KV store. 378 // ... 379} 380``` 381 382## KVManager 383 384Provides 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. 385 386### getKVStore 387 388getKVStore<T>(storeId: string, options: Options, callback: AsyncCallback<T>): void 389 390Creates and obtains a distributed KV store based on the specified **options** and **storeId**. This API uses an asynchronous callback to return the result. 391 392> **NOTE** 393> 394> If the database file cannot be opened (for example, the file header is damaged) when an existing distributed KV store is obtained, the automatic rebuild logic will be triggered to return a newly created distributed KV store instance. For important data that cannot be regenerated, you are advised to use the backup and restore feature to prevent data loss. For details, see [Database Backup and Restoration](../../database/data-backup-and-restore.md). 395 396**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 397 398**Parameters** 399 400| Name | Type | Mandatory| Description | 401| -------- | ---------------------- | ---- | ------------------------------------------------------------ | 402| 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.| 403| options | [Options](#options) | Yes | Configuration of the KV store to create. | 404| callback | AsyncCallback<T> | Yes | Callback used to return the **SingleKVStore** or **DeviceKVStore** instance created.| 405 406**Error codes** 407 408For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 409 410| ID| **Error Message** | 411| ------------ | ------------------------------------------- | 412| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 413| 15100002 | Open existed database with changed options. | 414| 15100003 | Database corrupted. | 415 416**Example** 417 418```ts 419import { BusinessError } from '@kit.BasicServicesKit'; 420 421let kvStore: distributedKVStore.SingleKVStore | null = null; 422try { 423 const options: distributedKVStore.Options = { 424 createIfMissing: true, 425 encrypt: false, 426 backup: false, 427 autoSync: false, 428 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 429 securityLevel: distributedKVStore.SecurityLevel.S3 430 }; 431 kvManager.getKVStore('storeId', options, (err: BusinessError, store: distributedKVStore.SingleKVStore) => { 432 if (err) { 433 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 434 return; 435 } 436 console.info("Succeeded in getting KVStore"); 437 kvStore = store; 438 }); 439} catch (e) { 440 let error = e as BusinessError; 441 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 442} 443if (kvStore !== null) { 444 kvStore = kvStore as distributedKVStore.SingleKVStore; 445 // Perform subsequent data operations, such as adding, deleting, modifying, and querying data, and subscribing to data changes. 446 // ... 447} 448``` 449 450### getKVStore 451 452getKVStore<T>(storeId: string, options: Options): Promise<T> 453 454Creates and obtains a distributed KV store based on the specified **options** and **storeId**. This API uses a promise to return the result. 455 456> **NOTE** 457> 458> If the database file cannot be opened (for example, the file header is damaged) when an existing distributed KV store is obtained, the automatic rebuild logic will be triggered to return a newly created distributed KV store instance. For important data that cannot be regenerated, you are advised to use the backup and restore feature to prevent data loss. For details, see [Database Backup and Restoration](../../database/data-backup-and-restore.md). 459 460**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 461 462**Parameters** 463 464| Name | Type | Mandatory| Description | 465| ------- | ------------------- | ---- | ------------------------------------------------------------ | 466| 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.| 467| options | [Options](#options) | Yes | Configuration of the KV store to create. | 468 469**Return value** 470 471| Type | Description | 472| ---------------- | ------------------------------------------------------------ | 473| Promise<T> | Promise used to return the **SingleKVStore** or **DeviceKVStore** instance created.| 474 475**Error codes** 476 477For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 478 479| ID| **Error Message** | 480| ------------ | ------------------------------------------- | 481| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed.| 482| 15100002 | Open existed database with changed options. | 483| 15100003 | Database corrupted. | 484 485**Example** 486 487```ts 488import { BusinessError } from '@kit.BasicServicesKit'; 489 490let kvStore: distributedKVStore.SingleKVStore | null = null; 491try { 492 const options: distributedKVStore.Options = { 493 createIfMissing: true, 494 encrypt: false, 495 backup: false, 496 autoSync: false, 497 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 498 securityLevel: distributedKVStore.SecurityLevel.S3 499 }; 500 kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options).then((store: distributedKVStore.SingleKVStore) => { 501 console.info("Succeeded in getting KVStore"); 502 kvStore = store; 503 }).catch((err: BusinessError) => { 504 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 505 }); 506} catch (e) { 507 let error = e as BusinessError; 508 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 509} 510``` 511 512### closeKVStore 513 514closeKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void 515 516Closes a distributed KV store. This API uses an asynchronous callback to return the result. 517 518**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 519 520**Parameters** 521 522| Name | Type | Mandatory| Description | 523| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 524| appId | string | Yes | Bundle name of the application. The value cannot be empty or exceed 256 bytes. | 525| 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.| 526| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 527 528**Error codes** 529 530For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 531 532| ID| **Error Message** | 533| ------------ | ------------------------------------------- | 534| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Parameter verification failed.| 535 536**Example** 537 538```ts 539import { BusinessError } from '@kit.BasicServicesKit'; 540 541let kvStore: distributedKVStore.SingleKVStore | null = null; 542const options: distributedKVStore.Options = { 543 createIfMissing: true, 544 encrypt: false, 545 backup: false, 546 autoSync: false, 547 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 548 schema: undefined, 549 securityLevel: distributedKVStore.SecurityLevel.S3 550} 551try { 552 kvManager.getKVStore('storeId', options, async (err: BusinessError, store: distributedKVStore.SingleKVStore | null) => { 553 if (err != undefined) { 554 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 555 return; 556 } 557 console.info('Succeeded in getting KVStore'); 558 kvStore = store; 559 kvStore = null; 560 store = null; 561 kvManager.closeKVStore('appId', 'storeId', (err: BusinessError)=> { 562 if (err != undefined) { 563 console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`); 564 return; 565 } 566 console.info('Succeeded in closing KVStore'); 567 }); 568 }); 569} catch (e) { 570 let error = e as BusinessError; 571 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 572} 573``` 574 575### closeKVStore 576 577closeKVStore(appId: string, storeId: string): Promise<void> 578 579Closes a distributed KV store. This API uses a promise to return the result. 580 581**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 582 583**Parameters** 584 585| Name | Type| Mandatory| Description | 586| ------- | -------- | ---- | ------------------------------------------------------------ | 587| appId | string | Yes | Bundle name of the application. The value cannot be empty or exceed 256 bytes. | 588| 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.| 589 590**Return value** 591 592| Type | Description | 593| -------------- | ------------------------- | 594| Promise\<void> | Promise that returns no value.| 595 596**Error codes** 597 598For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 599 600| ID| **Error Message** | 601| ------------ | ------------------------------------------- | 602| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Parameter verification failed.| 603 604**Example** 605 606```ts 607import { BusinessError } from '@kit.BasicServicesKit'; 608 609let kvStore: distributedKVStore.SingleKVStore | null = null; 610 611const options: distributedKVStore.Options = { 612 createIfMissing: true, 613 encrypt: false, 614 backup: false, 615 autoSync: false, 616 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 617 schema: undefined, 618 securityLevel: distributedKVStore.SecurityLevel.S3 619} 620try { 621 kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options).then(async (store: distributedKVStore.SingleKVStore | null) => { 622 console.info('Succeeded in getting KVStore'); 623 kvStore = store; 624 kvStore = null; 625 store = null; 626 kvManager.closeKVStore('appId', 'storeId').then(() => { 627 console.info('Succeeded in closing KVStore'); 628 }).catch((err: BusinessError) => { 629 console.error(`Failed to close KVStore.code is ${err.code},message is ${err.message}`); 630 }); 631 }).catch((err: BusinessError) => { 632 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 633 }); 634} catch (e) { 635 let error = e as BusinessError; 636 console.error(`Failed to close KVStore.code is ${error.code},message is ${error.message}`); 637} 638``` 639 640### deleteKVStore 641 642deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void 643 644Deletes a distributed KV store. This API uses an asynchronous callback to return the result. 645 646**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 647 648**Parameters** 649 650| Name | Type | Mandatory| Description | 651| -------- | ------------------------- | ---- | ------------------------------------------------------------ | 652| appId | string | Yes | Bundle name of the application. The value cannot be empty or exceed 256 bytes. | 653| 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.| 654| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 655 656**Error codes** 657 658For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 659 660| ID| **Error Message**| 661| ------------ | ------------ | 662| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Parameter verification failed.| 663| 15100004 | Not found. | 664 665**Example** 666 667```ts 668import { BusinessError } from '@kit.BasicServicesKit'; 669 670let kvStore: distributedKVStore.SingleKVStore | null = null; 671 672const options: distributedKVStore.Options = { 673 createIfMissing: true, 674 encrypt: false, 675 backup: false, 676 autoSync: false, 677 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 678 schema: undefined, 679 securityLevel: distributedKVStore.SecurityLevel.S3 680} 681try { 682 kvManager.getKVStore('store', options, async (err: BusinessError, store: distributedKVStore.SingleKVStore | null) => { 683 if (err != undefined) { 684 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 685 return; 686 } 687 console.info('Succeeded in getting KVStore'); 688 kvStore = store; 689 kvStore = null; 690 store = null; 691 kvManager.deleteKVStore('appId', 'storeId', (err: BusinessError) => { 692 if (err != undefined) { 693 console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`); 694 return; 695 } 696 console.info(`Succeeded in deleting KVStore`); 697 }); 698 }); 699} catch (e) { 700 let error = e as BusinessError; 701 console.error(`Failed to delete KVStore.code is ${error.code},message is ${error.message}`); 702} 703``` 704 705### deleteKVStore 706 707deleteKVStore(appId: string, storeId: string): Promise<void> 708 709Deletes a distributed KV store. This API uses a promise to return the result. 710 711**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 712 713**Parameters** 714 715| Name | Type| Mandatory| Description | 716| ------- | -------- | ---- | ------------------------------------------------------------ | 717| appId | string | Yes | Bundle name of the application. The value cannot be empty or exceed 256 bytes. | 718| 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.| 719 720**Return value** 721 722| Type | Description | 723| ------------------- | ------------------------- | 724| Promise<void> | Promise that returns no value.| 725 726**Error codes** 727 728For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 729 730| ID| **Error Message**| 731| ------------ | ------------ | 732| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Parameter verification failed.| 733| 15100004 | Not found. | 734 735**Example** 736 737```ts 738import { BusinessError } from '@kit.BasicServicesKit'; 739 740let kvStore: distributedKVStore.SingleKVStore | null = null; 741 742const options: distributedKVStore.Options = { 743 createIfMissing: true, 744 encrypt: false, 745 backup: false, 746 autoSync: false, 747 kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, 748 schema: undefined, 749 securityLevel: distributedKVStore.SecurityLevel.S3 750} 751try { 752 kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options).then(async (store: distributedKVStore.SingleKVStore | null) => { 753 console.info('Succeeded in getting KVStore'); 754 kvStore = store; 755 kvStore = null; 756 store = null; 757 kvManager.deleteKVStore('appId', 'storeId').then(() => { 758 console.info('Succeeded in deleting KVStore'); 759 }).catch((err: BusinessError) => { 760 console.error(`Failed to delete KVStore.code is ${err.code},message is ${err.message}`); 761 }); 762 }).catch((err: BusinessError) => { 763 console.error(`Failed to get KVStore.code is ${err.code},message is ${err.message}`); 764 }); 765} catch (e) { 766 let error = e as BusinessError; 767 console.error(`Failed to delete KVStore.code is ${error.code},message is ${error.message}`); 768} 769``` 770 771### getAllKVStoreId 772 773getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void 774 775Obtains 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. 776 777**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 778 779**Parameters** 780 781| Name | Type | Mandatory| Description | 782| -------- | ----------------------------- | ---- | --------------------------------------------------- | 783| appId | string | Yes | Bundle name of the application. The value cannot be empty or exceed 256 bytes. | 784| callback | AsyncCallback<string[]> | Yes | Callback used to return the IDs of all the distributed KV stores created.| 785 786**Error codes** 787 788For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 789 790| ID| **Error Message**| 791| ------------ | ------------ | 792| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Parameter verification failed.| 793 794**Example** 795 796```ts 797import { BusinessError } from '@kit.BasicServicesKit'; 798 799try { 800 kvManager.getAllKVStoreId('appId', (err: BusinessError, data: string[]) => { 801 if (err != undefined) { 802 console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`); 803 return; 804 } 805 console.info('Succeeded in getting AllKVStoreId'); 806 console.info(`GetAllKVStoreId size = ${data.length}`); 807 }); 808} catch (e) { 809 let error = e as BusinessError; 810 console.error(`Failed to get AllKVStoreId.code is ${error.code},message is ${error.message}`); 811} 812``` 813 814### getAllKVStoreId 815 816getAllKVStoreId(appId: string): Promise<string[]> 817 818Obtains 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. 819 820**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 821 822**Parameters** 823 824| Name| Type| Mandatory| Description | 825| ------ | -------- | ---- | ---------------------- | 826| appId | string | Yes | Bundle name of the application. The value cannot be empty or exceed 256 bytes.| 827 828**Return value** 829 830| Type | Description | 831| ----------------------- | ------------------------------------------------------ | 832| Promise<string[]> | Promise used to return the IDs of all the distributed KV stores created.| 833 834**Error codes** 835 836For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 837 838| ID| **Error Message**| 839| ------------ | ------------ | 840| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Parameter verification failed.| 841 842**Example** 843 844```ts 845import { BusinessError } from '@kit.BasicServicesKit'; 846 847try { 848 console.info('GetAllKVStoreId'); 849 kvManager.getAllKVStoreId('appId').then((data: string[]) => { 850 console.info('Succeeded in getting AllKVStoreId'); 851 console.info(`GetAllKVStoreId size = ${data.length}`); 852 }).catch((err: BusinessError) => { 853 console.error(`Failed to get AllKVStoreId.code is ${err.code},message is ${err.message}`); 854 }); 855} catch (e) { 856 let error = e as BusinessError; 857 console.error(`Failed to get AllKVStoreId.code is ${error.code},message is ${error.message}`); 858} 859``` 860 861### on('distributedDataServiceDie') 862 863on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void 864 865Subscribes 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 cross-device sync completion notifications again. In addition, an error will be returned for a sync operation. 866 867**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 868 869**Parameters** 870 871| Name | Type | Mandatory| Description | 872| ------------- | -------------------- | ---- | ------------------------------------------------------------ | 873| event | string | Yes | Event type. The value is **distributedDataServiceDie**, which indicates the termination of the distributed data service.| 874| deathCallback | Callback<void> | Yes | Callback used to return the result. If the subscription is successful, **err** is **undefined**. Otherwise, **err** is an error object. | 875 876**Error codes** 877 878For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 879 880| ID| **Error Message**| 881| ------------ | ------------ | 882| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed.| 883 884**Example** 885 886```ts 887import { BusinessError } from '@kit.BasicServicesKit'; 888 889try { 890 console.info('KVManagerOn'); 891 const deathCallback = () => { 892 console.info('death callback call'); 893 } 894 kvManager.on('distributedDataServiceDie', deathCallback); 895} catch (e) { 896 let error = e as BusinessError; 897 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 898} 899``` 900 901### off('distributedDataServiceDie') 902 903off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void 904 905Unsubscribes 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. 906 907**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 908 909**Parameters** 910 911| Name | Type | Mandatory| Description | 912| ------------- | -------------------- | ---- | ------------------------------------------------------------ | 913| event | string | Yes | Event type. The value is **distributedDataServiceDie**, which indicates the termination of the distributed data service.| 914| deathCallback | Callback<void> | No | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for the **distributedDataServiceDie** event. | 915 916**Error codes** 917 918For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 919 920| ID| **Error Message**| 921| ------------ | ------------ | 922| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 923 924**Example** 925 926```ts 927import { BusinessError } from '@kit.BasicServicesKit'; 928 929try { 930 console.info('KVManagerOff'); 931 const deathCallback = () => { 932 console.info('death callback call'); 933 } 934 kvManager.off('distributedDataServiceDie', deathCallback); 935} catch (e) { 936 let error = e as BusinessError; 937 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 938} 939``` 940 941## KVStoreResultSet 942 943Provides APIs for obtaining the distributed KV store result sets. A maximum of eight result sets can be opened at a time. 944 945Before calling any API in **KVStoreResultSet**, you must use **[getKVStore](#getkvstore)** to construct a **SingleKVStore** or **DeviceKVStore** instance. 946 947> **NOTE** 948> 949> The cursor start position of **KVStoreResultSet** is **-1**. 950 951### getCount 952 953getCount(): number 954 955Obtains the total number of rows in the result set. 956 957**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 958 959**Return value** 960 961| Type | Description | 962| ------ | ------------------ | 963| number | Total number of rows obtained.| 964 965**Example** 966 967```ts 968import { BusinessError } from '@kit.BasicServicesKit'; 969 970try { 971 let resultSet: distributedKVStore.KVStoreResultSet; 972 let count: number; 973 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 974 console.info('getResultSet succeed.'); 975 resultSet = result; 976 count = resultSet.getCount(); 977 console.info("getCount succeed:" + count); 978 }).catch((err: BusinessError) => { 979 console.error('getResultSet failed: ' + err); 980 }); 981} catch (e) { 982 console.error("getCount failed: " + e); 983} 984``` 985 986### getPosition 987 988getPosition(): number 989 990Obtains 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). 991 992**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 993 994**Return value** 995 996| Type | Description | 997| ------ | ------------------ | 998| 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.| 999 1000**Example** 1001 1002```ts 1003import { BusinessError } from '@kit.BasicServicesKit'; 1004 1005try { 1006 let resultSet: distributedKVStore.KVStoreResultSet; 1007 let position: number; 1008 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1009 console.info('getResultSet succeeded.'); 1010 resultSet = result; 1011 position = resultSet.getPosition(); 1012 console.info("getPosition succeed:" + position); 1013 }).catch((err: BusinessError) => { 1014 console.error('getResultSet failed: ' + err); 1015 }); 1016} catch (e) { 1017 console.error("getPosition failed: " + e); 1018} 1019``` 1020 1021### moveToFirst 1022 1023moveToFirst(): boolean 1024 1025Moves the data read position to the first row. If the result set is empty, **false** will be returned. 1026 1027**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1028 1029**Return value** 1030 1031| Type | Description | 1032| ------- | ----------------------------------------------- | 1033| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 1034 1035**Example** 1036 1037```ts 1038import { BusinessError } from '@kit.BasicServicesKit'; 1039 1040try { 1041 let resultSet: distributedKVStore.KVStoreResultSet; 1042 let moved: boolean; 1043 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1044 console.info('getResultSet succeed.'); 1045 resultSet = result; 1046 moved = resultSet.moveToFirst(); 1047 console.info("moveToFirst succeed: " + moved); 1048 }).catch((err: BusinessError) => { 1049 console.error('getResultSet failed: ' + err); 1050 }); 1051} catch (e) { 1052 console.error("moveToFirst failed " + e); 1053} 1054``` 1055 1056### moveToLast 1057 1058moveToLast(): boolean 1059 1060Moves the data read position to the last row. If the result set is empty, **false** will be returned. 1061 1062**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1063 1064**Return value** 1065 1066| Type | Description | 1067| ------- | ----------------------------------------------- | 1068| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 1069 1070**Example** 1071 1072```ts 1073import { BusinessError } from '@kit.BasicServicesKit'; 1074 1075try { 1076 let resultSet: distributedKVStore.KVStoreResultSet; 1077 let moved: boolean; 1078 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1079 console.info('getResultSet succeed.'); 1080 resultSet = result; 1081 moved = resultSet.moveToLast(); 1082 console.info("moveToLast succeed:" + moved); 1083 }).catch((err: BusinessError) => { 1084 console.error('getResultSet failed: ' + err); 1085 }); 1086} catch (e) { 1087 console.error("moveToLast failed: " + e); 1088} 1089``` 1090 1091### moveToNext 1092 1093moveToNext(): boolean 1094 1095Moves 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. 1096 1097**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1098 1099**Return value** 1100 1101| Type | Description | 1102| ------- | ----------------------------------------------- | 1103| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 1104 1105**Example** 1106 1107```ts 1108import { BusinessError } from '@kit.BasicServicesKit'; 1109 1110try { 1111 let resultSet: distributedKVStore.KVStoreResultSet; 1112 let moved: boolean; 1113 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1114 console.info('getResultSet succeed.'); 1115 resultSet = result; 1116 do { 1117 moved = resultSet.moveToNext(); 1118 console.info("moveToNext succeed: " + moved); 1119 } while (moved) 1120 }).catch((err: BusinessError) => { 1121 console.error('getResultSet failed: ' + err); 1122 }); 1123} catch (e) { 1124 console.error("moveToNext failed: " + e); 1125} 1126``` 1127 1128### moveToPrevious 1129 1130moveToPrevious(): boolean 1131 1132Moves 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. 1133 1134**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1135 1136**Return value** 1137 1138| Type | Description | 1139| ------- | ----------------------------------------------- | 1140| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 1141 1142**Example** 1143 1144```ts 1145import { BusinessError } from '@kit.BasicServicesKit'; 1146 1147try { 1148 let resultSet: distributedKVStore.KVStoreResultSet; 1149 let moved: boolean; 1150 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1151 console.info('getResultSet succeed.'); 1152 resultSet = result; 1153 moved = resultSet.moveToLast(); 1154 moved = resultSet.moveToPrevious(); 1155 console.info("moveToPrevious succeed:" + moved); 1156 }).catch((err: BusinessError) => { 1157 console.error('getResultSet failed: ' + err); 1158 }); 1159} catch (e) { 1160 console.error("moveToPrevious failed: " + e); 1161} 1162``` 1163 1164### move 1165 1166move(offset: number): boolean 1167 1168Moves 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. 1169 1170**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1171 1172**Parameters** 1173 1174| Name| Type| Mandatory| Description | 1175| ------ | -------- | ---- | ------------------------------------------------------------ | 1176| offset | number | Yes | Offset to move the data read position. A positive value means to move forward; a negative value means to move backward. If the cursor is beyond the start or end position of the result set, **false** is returned.| 1177 1178**Return value** 1179 1180| Type | Description | 1181| ------- | ----------------------------------------------- | 1182| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 1183 1184**Error codes** 1185 1186For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1187 1188| ID| **Error Message**| 1189| ------------ | ------------ | 1190| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 1191 1192**Example** 1193 1194```ts 1195import { BusinessError } from '@kit.BasicServicesKit'; 1196 1197try { 1198 let resultSet: distributedKVStore.KVStoreResultSet; 1199 let moved: boolean; 1200 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1201 console.info('Succeeded in getting resultSet'); 1202 resultSet = result; 1203 moved = resultSet.move(2); // If the current position is 0, move the read position forward by two rows, that is, move to row 3. 1204 console.info(`Succeeded in moving.moved = ${moved}`); 1205 }).catch((err: BusinessError) => { 1206 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 1207 }); 1208} catch (e) { 1209 let error = e as BusinessError; 1210 console.error(`Failed to move.code is ${error.code},message is ${error.message}`); 1211} 1212``` 1213 1214### moveToPosition 1215 1216moveToPosition(position: number): boolean 1217 1218Moves the data read position from 0 to an absolute position. 1219 1220**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1221 1222**Parameters** 1223 1224| Name | Type| Mandatory| Description | 1225| -------- | -------- | ---- | -------------- | 1226| position | number | Yes | Absolute position to move to. If the absolute position exceeds the start or end position of the result set, **false** is returned.| 1227 1228**Return value** 1229 1230| Type | Description | 1231| ------- | ----------------------------------------------- | 1232| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| 1233 1234**Error codes** 1235 1236For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1237 1238| ID| **Error Message**| 1239| ------------ | ------------ | 1240| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 1241 1242**Example** 1243 1244```ts 1245import { BusinessError } from '@kit.BasicServicesKit'; 1246 1247try { 1248 let resultSet: distributedKVStore.KVStoreResultSet; 1249 let moved: boolean; 1250 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1251 console.info('Succeeded in getting resultSet'); 1252 resultSet = result; 1253 moved = resultSet.moveToPosition(1); 1254 console.info(`Succeeded in moving to position.moved=${moved}`); 1255 }).catch((err: BusinessError) => { 1256 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 1257 }); 1258} catch (e) { 1259 let error = e as BusinessError; 1260 console.error(`Failed to move to position.code is ${error.code},message is ${error.message}`); 1261} 1262``` 1263 1264### isFirst 1265 1266isFirst(): boolean 1267 1268Checks whether the data read position is the first row. 1269 1270**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1271 1272**Return value** 1273 1274| Type | Description | 1275| ------- | ------------------------------------------------------------ | 1276| boolean | Returns **true** if the first row is being read; returns **false** otherwise.| 1277 1278**Example** 1279 1280```ts 1281import { BusinessError } from '@kit.BasicServicesKit'; 1282 1283try { 1284 let resultSet: distributedKVStore.KVStoreResultSet; 1285 let isfirst: boolean; 1286 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1287 console.info('getResultSet succeed.'); 1288 resultSet = result; 1289 isfirst = resultSet.isFirst(); 1290 console.info("Check isFirst succeed:" + isfirst); 1291 }).catch((err: BusinessError) => { 1292 console.error('getResultSet failed: ' + err); 1293 }); 1294} catch (e) { 1295 console.error("Check isFirst failed: " + e); 1296} 1297``` 1298 1299### isLast 1300 1301isLast(): boolean 1302 1303Checks whether the data read position is the last row. 1304 1305**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1306 1307**Return value** 1308 1309| Type | Description | 1310| ------- | ------------------------------------------------------------ | 1311| boolean | Returns **true** if the last row is being read; returns **false** otherwise.| 1312 1313**Example** 1314 1315```ts 1316import { BusinessError } from '@kit.BasicServicesKit'; 1317 1318try { 1319 let resultSet: distributedKVStore.KVStoreResultSet; 1320 let islast: boolean; 1321 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1322 console.info('getResultSet succeed.'); 1323 resultSet = result; 1324 islast = resultSet.isLast(); 1325 console.info("Check isLast succeed: " + islast); 1326 }).catch((err: BusinessError) => { 1327 console.error('getResultSet failed: ' + err); 1328 }); 1329} catch (e) { 1330 console.error("Check isLast failed: " + e); 1331} 1332``` 1333 1334### isBeforeFirst 1335 1336isBeforeFirst(): boolean 1337 1338Checks whether the data read position is before the first row. 1339 1340**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1341 1342**Return value** 1343 1344| Type | Description | 1345| ------- | ------------------------------------------------------------ | 1346| boolean | Returns **true** if the data read position is before the first row; returns **false** otherwise.| 1347 1348**Example** 1349 1350```ts 1351import { BusinessError } from '@kit.BasicServicesKit'; 1352 1353try { 1354 let resultSet: distributedKVStore.KVStoreResultSet; 1355 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1356 console.info('getResultSet succeed.'); 1357 resultSet = result; 1358 let isbeforefirst = resultSet.isBeforeFirst(); 1359 console.info("Check isBeforeFirst succeed: " + isbeforefirst); 1360 }).catch((err: BusinessError) => { 1361 console.error('getResultSet failed: ' + err); 1362 }); 1363} catch (e) { 1364 console.error("Check isBeforeFirst failed: " + e); 1365} 1366``` 1367 1368### isAfterLast 1369 1370isAfterLast(): boolean 1371 1372Checks whether the data read position is after the last row. 1373 1374**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1375 1376**Return value** 1377 1378| Type | Description | 1379| ------- | ------------------------------------------------------------ | 1380| boolean | Returns **true** if the data read position is after the last row; returns **false** otherwise.| 1381 1382**Example** 1383 1384```ts 1385import { BusinessError } from '@kit.BasicServicesKit'; 1386 1387try { 1388 let resultSet: distributedKVStore.KVStoreResultSet; 1389 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1390 console.info('getResultSet succeed.'); 1391 resultSet = result; 1392 let isafterlast = resultSet.isAfterLast(); 1393 console.info("Check isAfterLast succeed:" + isafterlast); 1394 }).catch((err: BusinessError) => { 1395 console.error('getResultSet failed: ' + err); 1396 }); 1397} catch (e) { 1398 console.error("Check isAfterLast failed: " + e); 1399} 1400``` 1401 1402### getEntry 1403 1404getEntry(): Entry 1405 1406Obtains the KV pair from the current position. 1407 1408**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1409 1410**Return value** 1411 1412| Type | Description | 1413| --------------- | ------------ | 1414| [Entry](#entry) | KV pair obtained.| 1415 1416**Example** 1417 1418```ts 1419import { BusinessError } from '@kit.BasicServicesKit'; 1420 1421try { 1422 let resultSet: distributedKVStore.KVStoreResultSet; 1423 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 1424 console.info('getResultSet succeed.'); 1425 resultSet = result; 1426 let entry = resultSet.getEntry(); 1427 console.info("getEntry succeed:" + JSON.stringify(entry)); 1428 }).catch((err: BusinessError) => { 1429 console.error('getResultSet failed: ' + err); 1430 }); 1431} catch (e) { 1432 console.error("getEntry failed: " + e); 1433} 1434``` 1435 1436## Query 1437 1438Provides methods to create a **Query** object, which defines different data query criteria. A **Query** object supports a maximum of 256 predicates. 1439 1440**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 1441 1442### constructor 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 | Maximum number of results to query. The value must be a non-negative integer.<br>If the value is a negative number, the entire result set is queried.| 2230| offset | number | Yes | Start position of the query result. The value must be a non-negative integer.<br>If the value is a negative number, the entire result set is queried.<br>If **offset** exceeds the end of the result set, the query result is empty.| 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 to set, which 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 2538Provides APIs for data management in a single KV store, such as adding data, deleting data, and subscribing to data changes or across-device data sync completion events. 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** 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). 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 | Network 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** 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). 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 | Network 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 cross-device 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 across devices. The value **true** means to enable data sync across devices, and the value **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 cross-device 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 across devices. The value **true** means to enable data sync across devices, and the value **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 for cross-device data sync. This API uses an asynchronous callback to return the result. 4857 4858> **NOTE** 4859> 4860> After the default delay is set, calling [sync](#sync) will not trigger the cross-device data sync immediately. Instead, the data sync will be executed only after the specified delay duration. 4861 4862**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4863 4864**Parameters** 4865 4866| Name | Type | Mandatory| Description | 4867| --------------------- | ------------------------- | ---- | -------------------------------------------- | 4868| defaultAllowedDelayMs | number | Yes | Delay time to set, in ms.| 4869| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| 4870 4871**Error codes** 4872 4873For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 4874 4875| ID| **Error Message**| 4876| ------------ | ------------ | 4877| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 4878 4879**Example** 4880 4881```ts 4882import { BusinessError } from '@kit.BasicServicesKit'; 4883 4884try { 4885 const defaultAllowedDelayMs = 500; 4886 kvStore.setSyncParam(defaultAllowedDelayMs, (err: BusinessError) => { 4887 if (err != undefined) { 4888 console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`); 4889 return; 4890 } 4891 console.info('Succeeded in setting syncParam'); 4892 }); 4893} catch (e) { 4894 let error = e as BusinessError; 4895 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4896} 4897``` 4898 4899### setSyncParam 4900 4901setSyncParam(defaultAllowedDelayMs: number): Promise<void> 4902 4903Sets the default delay for cross-device data sync. This API uses a promise to return the result. 4904 4905> **NOTE** 4906> 4907> After the default delay is set, calling [sync](#sync) will not trigger the cross-device data sync immediately. Instead, the data sync will be executed only after the specified delay duration. 4908 4909**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4910 4911**Parameters** 4912 4913| Name | Type| Mandatory| Description | 4914| --------------------- | -------- | ---- | -------------------------------------------- | 4915| defaultAllowedDelayMs | number | Yes | Delay time to set, in ms.| 4916 4917**Return value** 4918 4919| Type | Description | 4920| ------------------- | ------------------------- | 4921| Promise<void> | Promise that returns no value.| 4922 4923**Error codes** 4924 4925For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 4926 4927| ID| **Error Message**| 4928| ------------ | ------------ | 4929| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 4930 4931**Example** 4932 4933```ts 4934import { BusinessError } from '@kit.BasicServicesKit'; 4935 4936try { 4937 const defaultAllowedDelayMs = 500; 4938 kvStore.setSyncParam(defaultAllowedDelayMs).then(() => { 4939 console.info('Succeeded in setting syncParam'); 4940 }).catch((err: BusinessError) => { 4941 console.error(`Failed to set syncParam.code is ${err.code},message is ${err.message}`); 4942 }); 4943} catch (e) { 4944 let error = e as BusinessError; 4945 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 4946} 4947``` 4948 4949### sync 4950 4951sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void 4952 4953Starts cross-device data sync manually. For details about the sync modes of KV stores, see [Cross-Device Synchronization of KV Stores](../../database/data-sync-of-kv-store.md). 4954> **NOTE** 4955> 4956> **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). 4957 4958**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 4959 4960**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 4961 4962**Parameters** 4963 4964| Name | Type | Mandatory| Description | 4965| --------- | --------------------- | ---- | ---------------------------------------------- | 4966| deviceIds | string[] | Yes | List of **networkId**s of the devices in the same networking environment to be synchronized.| 4967| mode | [SyncMode](#syncmode) | Yes | Sync mode. | 4968| delayMs | number | No | Delay time allowed, in ms. The default value is **0**. If **delayMs** is set, data sync will be executed **delayMs** after **sync()** is called. If **delayMs** is not set, the delay set in [setSyncParam](#setsyncparam) is used.| 4969 4970**Error codes** 4971 4972For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 4973 4974| ID| **Error Message** | 4975| ------------ | ------------------- | 4976| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 4977| 15100003 | Database corrupted. | 4978| 15100004 | Not found. | 4979 4980**Example** 4981 4982```ts 4983import { distributedDeviceManager } from '@kit.DistributedServiceKit'; 4984import { UIAbility } from '@kit.AbilityKit'; 4985import { BusinessError } from '@kit.BasicServicesKit'; 4986 4987let devManager: distributedDeviceManager.DeviceManager; 4988const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; 4989const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; 4990// create deviceManager 4991export default class EntryAbility extends UIAbility { 4992 onCreate() { 4993 let context = this.context; 4994 try { 4995 devManager = distributedDeviceManager.createDeviceManager(context.applicationInfo.name); 4996 let deviceIds: string[] = []; 4997 if (devManager != null) { 4998 let devices = devManager.getAvailableDeviceListSync(); 4999 for (let i = 0; i < devices.length; i++) { 5000 deviceIds[i] = devices[i].networkId as string; 5001 } 5002 } 5003 try { 5004 if (kvStore != null) { 5005 kvStore.on('syncComplete', (data: [string, number][]) => { 5006 console.info('Sync dataChange'); 5007 }); 5008 if (kvStore != null) { 5009 kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, (err: BusinessError) => { 5010 if (err != undefined) { 5011 console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); 5012 return; 5013 } 5014 console.info('Succeeded in putting data'); 5015 const mode = distributedKVStore.SyncMode.PULL_ONLY; 5016 if (kvStore != null) { 5017 kvStore.sync(deviceIds, mode, 1000); 5018 } 5019 }); 5020 } 5021 } 5022 } catch (e) { 5023 let error = e as BusinessError; 5024 console.error(`Failed to sync.code is ${error.code},message is ${error.message}`); 5025 } 5026 5027 } catch (err) { 5028 let error = err as BusinessError; 5029 console.error("createDeviceManager errCode:" + error.code + ",errMessage:" + error.message); 5030 } 5031 } 5032} 5033``` 5034 5035### sync 5036 5037sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void 5038 5039Starts cross-device data sync 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). 5040> **NOTE** 5041> 5042> **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). 5043 5044**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 5045 5046**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5047 5048**Parameters** 5049 5050| Name | Type | Mandatory| Description | 5051| --------- | --------------------- | ---- | ---------------------------------------------- | 5052| deviceIds | string[] | Yes | List of **networkId**s of the devices in the same networking environment to be synchronized.| 5053| mode | [SyncMode](#syncmode) | Yes | Sync mode. | 5054| query | [Query](#query) | Yes | **Query** object to match. | 5055| delayMs | number | No | Delay time allowed, in ms. The default value is **0**. If **delayMs** is set, data sync will be executed **delayMs** after **sync()** is called. If **delayMs** is not set, the delay set in [setSyncParam](#setsyncparam) is used.| 5056 5057**Error codes** 5058 5059For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5060 5061| ID| **Error Message** | 5062| ------------ | ------------------- | 5063| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 5064| 15100003 | Database corrupted. | 5065| 15100004 | Not found. | 5066 5067**Example** 5068 5069```ts 5070import { distributedDeviceManager } from '@kit.DistributedServiceKit'; 5071import { UIAbility } from '@kit.AbilityKit'; 5072import { BusinessError } from '@kit.BasicServicesKit'; 5073 5074let devManager: distributedDeviceManager.DeviceManager; 5075const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; 5076const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; 5077// create deviceManager 5078export default class EntryAbility extends UIAbility { 5079 onCreate() { 5080 let context = this.context; 5081 try { 5082 let devManager = distributedDeviceManager.createDeviceManager(context.applicationInfo.name); 5083 let deviceIds: string[] = []; 5084 if (devManager != null) { 5085 let devices = devManager.getAvailableDeviceListSync(); 5086 for (let i = 0; i < devices.length; i++) { 5087 deviceIds[i] = devices[i].networkId as string; 5088 } 5089 } 5090 try { 5091 if (kvStore != null) { 5092 kvStore.on('syncComplete', (data: [string, number][]) => { 5093 console.info('Sync dataChange'); 5094 }); 5095 if (kvStore != null) { 5096 kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, (err: BusinessError) => { 5097 if (err != undefined) { 5098 console.error(`Failed to sync.code is ${err.code},message is ${err.message}`); 5099 return; 5100 } 5101 console.info('Succeeded in putting data'); 5102 const mode = distributedKVStore.SyncMode.PULL_ONLY; 5103 const query = new distributedKVStore.Query(); 5104 query.prefixKey("batch_test"); 5105 query.deviceId(devManager.getLocalDeviceNetworkId()); 5106 if (kvStore != null) { 5107 kvStore.sync(deviceIds, query, mode, 1000); 5108 } 5109 }); 5110 } 5111 } 5112 } catch (e) { 5113 let error = e as BusinessError; 5114 console.error(`Failed to sync.code is ${error.code},message is ${error.message}`); 5115 } 5116 5117 } catch (err) { 5118 let error = err as BusinessError; 5119 console.error("createDeviceManager errCode:" + error.code + ",errMessage:" + error.message); 5120 } 5121 } 5122} 5123``` 5124 5125### on('dataChange') 5126 5127on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void 5128 5129Subscribes to data changes of the specified type. 5130 5131**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5132 5133**Parameters** 5134 5135| Name | Type | Mandatory| Description | 5136| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | 5137| event | string | Yes | Event type. The value is **dataChange**, which indicates a data change event.| 5138| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | 5139| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback used to return the object to be notified when the data changes.| 5140 5141**Error codes** 5142 5143For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5144 5145| ID| **Error Message** | 5146| ------------ | -------------------------------------- | 5147| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 5148| 15100001 | Over max limits. | 5149| 15100005 | Database or result set already closed. | 5150 5151**Example** 5152 5153```ts 5154import { BusinessError } from '@kit.BasicServicesKit'; 5155 5156try { 5157 kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, (data: distributedKVStore.ChangeNotification) => { 5158 console.info(`dataChange callback call data: ${data}`); 5159 }); 5160} catch (e) { 5161 let error = e as BusinessError; 5162 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 5163} 5164``` 5165 5166### on('syncComplete') 5167 5168on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void 5169 5170Subscribes to the cross-device data sync completion events. 5171 5172**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5173 5174**Parameters** 5175 5176| Name | Type | Mandatory| Description | 5177| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | 5178| event | string | Yes | Event type. The value is **syncComplete**, which indicates the sync completion event.| 5179| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return the sync completion event. | 5180 5181**Error codes** 5182 5183For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 5184 5185| ID| **Error Message** | 5186| ------------ | -------------------------------------- | 5187| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 5188 5189**Example** 5190 5191```ts 5192import { BusinessError } from '@kit.BasicServicesKit'; 5193 5194 5195const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; 5196const VALUE_TEST_FLOAT_ELEMENT = 321.12; 5197try { 5198 kvStore.on('syncComplete', (data: [string, number][]) => { 5199 console.info(`syncComplete ${data}`); 5200 }); 5201 kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then(() => { 5202 console.info('succeeded in putting'); 5203 }).catch((err: BusinessError) => { 5204 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 5205 }); 5206} catch (e) { 5207 let error = e as BusinessError; 5208 console.error(`Failed to subscribe syncComplete.code is ${error.code},message is ${error.message}`); 5209} 5210``` 5211 5212### off('dataChange') 5213 5214off(event:'dataChange', listener?: Callback<ChangeNotification>): void 5215 5216Unsubscribes from data changes. 5217 5218**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5219 5220**Parameters** 5221 5222| Name | Type | Mandatory| Description | 5223| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | 5224| event | string | Yes | Event type. The value is **dataChange**, which indicates data changes.| 5225| listener | Callback<[ChangeNotification](#changenotification)> | No | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for data changes.| 5226 5227**Error codes** 5228 5229For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5230 5231| ID| **Error Message** | 5232| ------------ | -------------------------------------- | 5233| 401 | Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 5234| 15100005 | Database or result set already closed. | 5235 5236**Example** 5237 5238```ts 5239import { BusinessError } from '@kit.BasicServicesKit'; 5240 5241class KvstoreModel { 5242 call(data: distributedKVStore.ChangeNotification) { 5243 console.info(`dataChange : ${data}`); 5244 } 5245 5246 subscribeDataChange() { 5247 try { 5248 if (kvStore != null) { 5249 kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); 5250 } 5251 } catch (err) { 5252 let error = err as BusinessError; 5253 console.error(`Failed to subscribeDataChange.code is ${error.code},message is ${error.message}`); 5254 } 5255 } 5256 5257 unsubscribeDataChange() { 5258 try { 5259 if (kvStore != null) { 5260 kvStore.off('dataChange', this.call); 5261 } 5262 } catch (err) { 5263 let error = err as BusinessError; 5264 console.error(`Failed to unsubscribeDataChange.code is ${error.code},message is ${error.message}`); 5265 } 5266 } 5267} 5268``` 5269 5270### off('syncComplete') 5271 5272off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void 5273 5274Unsubscribes from the cross-device data sync completion events. 5275 5276**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5277 5278**Parameters** 5279 5280| Name | Type | Mandatory| Description | 5281| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | 5282| event | string | Yes | Event type. The value is **syncComplete**, which indicates a sync completion event.| 5283| syncCallback | Callback<Array<[string, number]>> | No | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for data changes. | 5284 5285**Error codes** 5286 5287For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 5288 5289| ID| **Error Message** | 5290| ------------ | -------------------------------------- | 5291| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 5292 5293**Example** 5294 5295```ts 5296import { BusinessError } from '@kit.BasicServicesKit'; 5297 5298class KvstoreModel { 5299 call(data: [string, number][]) { 5300 console.info(`syncComplete : ${data}`); 5301 } 5302 5303 subscribeDataChange() { 5304 try { 5305 if (kvStore != null) { 5306 kvStore.on('syncComplete', this.call); 5307 } 5308 } catch (err) { 5309 let error = err as BusinessError; 5310 console.error(`Failed to subscribeDataChange.code is ${error.code},message is ${error.message}`); 5311 } 5312 } 5313 5314 unsubscribeDataChange() { 5315 try { 5316 if (kvStore != null) { 5317 kvStore.off('syncComplete', this.call); 5318 } 5319 } catch (err) { 5320 let error = err as BusinessError; 5321 console.error(`Failed to unsubscribeDataChange.code is ${error.code},message is ${error.message}`); 5322 } 5323 } 5324} 5325``` 5326 5327### getSecurityLevel 5328 5329getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void 5330 5331Obtains the security level of this KV store. This API uses an asynchronous callback to return the result. 5332 5333**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5334 5335**Parameters** 5336 5337| Name | Type | Mandatory| Description | 5338| -------- | ---------------------------------------------------- | ---- | -------------------------------- | 5339| callback | AsyncCallback<[SecurityLevel](#securitylevel)> | Yes | Callback used to return the security level of the KV store.| 5340 5341**Error codes** 5342 5343For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md). 5344 5345| ID| **Error Message** | 5346| ------------ | -------------------------------------- | 5347| 15100005 | Database or result set already closed. | 5348 5349**Example** 5350 5351```ts 5352import { BusinessError } from '@kit.BasicServicesKit'; 5353 5354try { 5355 kvStore.getSecurityLevel((err: BusinessError, data: distributedKVStore.SecurityLevel) => { 5356 if (err != undefined) { 5357 console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`); 5358 return; 5359 } 5360 console.info('Succeeded in getting securityLevel'); 5361 }); 5362} catch (e) { 5363 let error = e as BusinessError; 5364 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 5365} 5366``` 5367 5368### getSecurityLevel 5369 5370getSecurityLevel(): Promise<SecurityLevel> 5371 5372Obtains the security level of this KV store. This API uses a promise to return the result. 5373 5374**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5375 5376**Return value** 5377 5378| Type | Description | 5379| ---------------------------------------------- | ----------------------------------- | 5380| Promise<[SecurityLevel](#securitylevel)> | Promise used to return the security level of the KV store.| 5381 5382**Error codes** 5383 5384For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md). 5385 5386| ID| **Error Message** | 5387| ------------ | -------------------------------------- | 5388| 15100005 | Database or result set already closed. | 5389 5390**Example** 5391 5392```ts 5393import { BusinessError } from '@kit.BasicServicesKit'; 5394 5395try { 5396 kvStore.getSecurityLevel().then((data: distributedKVStore.SecurityLevel) => { 5397 console.info('Succeeded in getting securityLevel'); 5398 }).catch((err: BusinessError) => { 5399 console.error(`Failed to get SecurityLevel.code is ${err.code},message is ${err.message}`); 5400 }); 5401} catch (e) { 5402 let error = e as BusinessError; 5403 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 5404} 5405``` 5406 5407## DeviceKVStore 5408 5409Provides APIs for querying data in a device KV store and performing cross-device data sync. This class inherits from **SingleKVStore**. The **SingleKVStore** APIs such as **put** and **putBatch** can be used. 5410 5411Data 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. 5412 5413For 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. 5414 5415Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. 5416 5417### get 5418 5419get(key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 5420 5421Obtains the value of the specified key for this device. This API uses an asynchronous callback to return the result. 5422 5423**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5424 5425**Parameters** 5426 5427| Name | Type | Mandatory| Description | 5428| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 5429| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 5430| callback | AsyncCallback<boolean \| string \| number \| Uint8Array> | Yes | Callback used to return the value obtained. | 5431 5432**Error codes** 5433 5434For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5435 5436| ID| **Error Message** | 5437| ------------ | -------------------------------------- | 5438| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 5439| 15100003 | Database corrupted. | 5440| 15100004 | Not found. | 5441| 15100005 | Database or result set already closed. | 5442 5443**Example** 5444 5445```ts 5446import { BusinessError } from '@kit.BasicServicesKit'; 5447 5448const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 5449const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 5450try { 5451 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err: BusinessError) => { 5452 if (err != undefined) { 5453 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 5454 return; 5455 } 5456 console.info("Succeeded in putting"); 5457 if (kvStore != null) { 5458 kvStore.get(KEY_TEST_STRING_ELEMENT, (err: BusinessError, data: boolean | string | number | Uint8Array) => { 5459 if (err != undefined) { 5460 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 5461 return; 5462 } 5463 console.info(`Succeeded in getting data.data=${data}`); 5464 }); 5465 } 5466 }); 5467} catch (e) { 5468 let error = e as BusinessError; 5469 console.error(`Failed to get.code is ${error.code},message is ${error.message}`); 5470} 5471``` 5472 5473### get 5474 5475get(key: string): Promise<boolean | string | number | Uint8Array> 5476 5477Obtains the value of the specified key for this device. This API uses a promise to return the result. 5478 5479**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5480 5481**Parameters** 5482 5483| Name| Type | Mandatory| Description | 5484| ------ | ------ | ---- | ------------------------------------------------------------ | 5485| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| 5486 5487**Return value** 5488 5489| Type | Description | 5490| -------------------------------------------------------- | ------------------------------- | 5491| Promise<Uint8Array \| string \| boolean \| number> | Promise used to return the value obtained.| 5492 5493**Error codes** 5494 5495For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5496 5497| ID| **Error Message** | 5498| ------------ | -------------------------------------- | 5499| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 5500| 15100003 | Database corrupted. | 5501| 15100004 | Not found. | 5502| 15100005 | Database or result set already closed. | 5503 5504**Example** 5505 5506```ts 5507import { BusinessError } from '@kit.BasicServicesKit'; 5508 5509const KEY_TEST_STRING_ELEMENT = 'key_test_string'; 5510const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; 5511try { 5512 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(() => { 5513 console.info(`Succeeded in putting data`); 5514 if (kvStore != null) { 5515 kvStore.get(KEY_TEST_STRING_ELEMENT).then((data: boolean | string | number | Uint8Array) => { 5516 console.info(`Succeeded in getting data.data=${data}`); 5517 }).catch((err: BusinessError) => { 5518 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 5519 }); 5520 } 5521 }).catch((err: BusinessError) => { 5522 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 5523 }); 5524} catch (e) { 5525 let error = e as BusinessError; 5526 console.error(`Failed to get.code is ${error.code},message is ${error.message}`); 5527} 5528``` 5529 5530### get 5531 5532get(deviceId: string, key: string, callback: AsyncCallback<boolean | string | number | Uint8Array>): void 5533 5534Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. 5535> **NOTE** 5536> 5537> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 5538> For details about how to obtain **deviceId**, see [sync()](#sync). 5539 5540**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5541 5542**Parameters** 5543 5544| Name | Type| Mandatory | Description | 5545| ----- | ------ | ---- | ----------------------- | 5546| deviceId |string | Yes |ID of the target device. | 5547| key |string | Yes |Key of the value to obtain. It cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | 5548| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback used to return the value obtained. | 5549 5550**Error codes** 5551 5552For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5553 5554| ID| **Error Message** | 5555| ------------ | -------------------------------------- | 5556| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 5557| 15100003 | Database corrupted. | 5558| 15100004 | Not found. | 5559| 15100005 | Database or result set already closed. | 5560 5561**Example** 5562 5563```ts 5564import { BusinessError } from '@kit.BasicServicesKit'; 5565 5566const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 5567const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; 5568try { 5569 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async (err: BusinessError) => { 5570 if (err != undefined) { 5571 console.error(`Failed to put.code is ${err.code},message is ${err.message}`); 5572 return; 5573 } 5574 console.info('Succeeded in putting'); 5575 if (kvStore != null) { 5576 kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, (err: BusinessError, data: boolean | string | number | Uint8Array) => { 5577 if (err != undefined) { 5578 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 5579 return; 5580 } 5581 console.info('Succeeded in getting'); 5582 }); 5583 } 5584 }) 5585} catch (e) { 5586 let error = e as BusinessError; 5587 console.error(`Failed to get.code is ${error.code},message is ${error.message}`); 5588} 5589``` 5590 5591### get 5592 5593get(deviceId: string, key: string): Promise<boolean | string | number | Uint8Array> 5594 5595Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. 5596> **NOTE** 5597> 5598> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 5599> For details about how to obtain **deviceId**, see [sync()](#sync). 5600 5601**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5602 5603**Parameters** 5604 5605| Name | Type| Mandatory| Description | 5606| -------- | -------- | ---- | ------------------------ | 5607| deviceId | string | Yes | ID of the target device.| 5608| key | string | Yes | Key of the value to obtain. It cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | 5609 5610**Return value** 5611 5612| Type | Description | 5613| ------ | ------- | 5614|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value that matches the given condition.| 5615 5616**Error codes** 5617 5618For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5619 5620| ID| **Error Message** | 5621| ------------ | -------------------------------------- | 5622| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types; 3. Parameter verification failed. | 5623| 15100003 | Database corrupted. | 5624| 15100004 | Not found. | 5625| 15100005 | Database or result set already closed. | 5626 5627**Example** 5628 5629```ts 5630import { BusinessError } from '@kit.BasicServicesKit'; 5631 5632const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; 5633const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; 5634try { 5635 kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async () => { 5636 console.info('Succeeded in putting'); 5637 if (kvStore != null) { 5638 kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data: boolean | string | number | Uint8Array) => { 5639 console.info('Succeeded in getting'); 5640 }).catch((err: BusinessError) => { 5641 console.error(`Failed to get.code is ${err.code},message is ${err.message}`); 5642 }); 5643 } 5644 }).catch((error: BusinessError) => { 5645 console.error(`Failed to put.code is ${error.code},message is ${error.message}`); 5646 }); 5647} catch (e) { 5648 let error = e as BusinessError; 5649 console.error(`Failed to get.code is ${error.code},message is ${error.message}`); 5650} 5651``` 5652 5653### getEntries 5654 5655getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void 5656 5657Obtains all KV pairs that match the specified key prefix for this device. This API uses an asynchronous callback to return the result. 5658 5659**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5660 5661**Parameters** 5662 5663| Name | Type | Mandatory| Description | 5664| --------- | -------------------------------------- | ---- | ---------------------------------------- | 5665| 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.| 5666| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback used to return the KV pairs that match the specified prefix.| 5667 5668**Error codes** 5669 5670For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5671 5672| ID| **Error Message** | 5673| ------------ | -------------------------------------- | 5674| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 5675| 15100003 | Database corrupted. | 5676| 15100005 | Database or result set already closed. | 5677 5678**Example** 5679 5680```ts 5681import { BusinessError } from '@kit.BasicServicesKit'; 5682 5683try { 5684 let entries: distributedKVStore.Entry[] = []; 5685 for (let i = 0; i < 10; i++) { 5686 let key = 'batch_test_string_key'; 5687 let entry: distributedKVStore.Entry = { 5688 key: key + i, 5689 value: { 5690 type: distributedKVStore.ValueType.STRING, 5691 value: 'batch_test_string_value' 5692 } 5693 } 5694 entries.push(entry); 5695 } 5696 console.info(`entries: ${entries}`); 5697 kvStore.putBatch(entries, async (err: BusinessError) => { 5698 if (err != undefined) { 5699 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 5700 return; 5701 } 5702 console.info('Succeeded in putting Batch'); 5703 if (kvStore != null) { 5704 kvStore.getEntries('batch_test_string_key', (err: BusinessError, entries: distributedKVStore.Entry[]) => { 5705 if (err != undefined) { 5706 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 5707 return; 5708 } 5709 console.info('Succeeded in getting Entries'); 5710 console.info(`entries.length: ${entries.length}`); 5711 console.info(`entries[0]: ${entries[0]}`); 5712 }); 5713 } 5714 }); 5715} catch (e) { 5716 let error = e as BusinessError; 5717 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `); 5718} 5719``` 5720 5721### getEntries 5722 5723getEntries(keyPrefix: string): Promise<Entry[]> 5724 5725Obtains all KV pairs that match the specified key prefix for this device. This API uses a promise to return the result. 5726 5727**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5728 5729**Parameters** 5730 5731| Name | Type | Mandatory| Description | 5732| --------- | ------ | ---- | -------------------- | 5733| 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.| 5734 5735**Return value** 5736 5737| Type | Description | 5738| -------------------------------- | ------------------------------------------- | 5739| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified prefix.| 5740 5741**Error codes** 5742 5743For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5744 5745| ID| **Error Message** | 5746| ------------ | -------------------------------------- | 5747| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 5748| 15100003 | Database corrupted. | 5749| 15100005 | Database or result set already closed. | 5750 5751**Example** 5752 5753```ts 5754import { BusinessError } from '@kit.BasicServicesKit'; 5755 5756try { 5757 let entries: distributedKVStore.Entry[] = []; 5758 for (let i = 0; i < 10; i++) { 5759 let key = 'batch_test_string_key'; 5760 let entry: distributedKVStore.Entry = { 5761 key: key + i, 5762 value: { 5763 type: distributedKVStore.ValueType.STRING, 5764 value: 'batch_test_string_value' 5765 } 5766 } 5767 entries.push(entry); 5768 } 5769 console.info(`entries: ${entries}`); 5770 kvStore.putBatch(entries).then(async () => { 5771 console.info('Succeeded in putting Batch'); 5772 if (kvStore != null) { 5773 kvStore.getEntries('batch_test_string_key').then((entries: distributedKVStore.Entry[]) => { 5774 console.info('Succeeded in getting Entries'); 5775 console.info(`PutBatch ${entries}`); 5776 }).catch((err: BusinessError) => { 5777 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 5778 }); 5779 } 5780 }).catch((err: BusinessError) => { 5781 console.error(`Failed to put Batch.code is ${err.code},message is ${err.message}`); 5782 }); 5783} catch (e) { 5784 let error = e as BusinessError; 5785 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message} `); 5786} 5787``` 5788 5789### getEntries 5790 5791getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void 5792 5793Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. 5794> **NOTE** 5795> 5796> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 5797> For details about how to obtain **deviceId**, see [sync()](#sync). 5798 5799**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5800 5801**Parameters** 5802 5803| Name | Type | Mandatory| Description | 5804| --------- | -------------------------------------- | ---- | ---------------------------------------------- | 5805| deviceId | string | Yes | ID of the target device. | 5806| 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.| 5807| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback used to return the KV pairs obtained.| 5808 5809**Error codes** 5810 5811For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5812 5813| ID| **Error Message** | 5814| ------------ | -------------------------------------- | 5815| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 5816| 15100003 | Database corrupted. | 5817| 15100005 | Database or result set already closed. | 5818 5819**Example** 5820 5821```ts 5822import { BusinessError } from '@kit.BasicServicesKit'; 5823 5824try { 5825 let entries: distributedKVStore.Entry[] = []; 5826 for (let i = 0; i < 10; i++) { 5827 let key = 'batch_test_string_key'; 5828 let entry: distributedKVStore.Entry = { 5829 key: key + i, 5830 value: { 5831 type: distributedKVStore.ValueType.STRING, 5832 value: 'batch_test_string_value' 5833 } 5834 } 5835 entries.push(entry); 5836 } 5837 console.info(`entries : ${entries}`); 5838 kvStore.putBatch(entries, async (err: BusinessError) => { 5839 if (err != undefined) { 5840 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 5841 return; 5842 } 5843 console.info('Succeeded in putting batch'); 5844 if (kvStore != null) { 5845 kvStore.getEntries('localDeviceId', 'batch_test_string_key', (err: BusinessError, entries: distributedKVStore.Entry[]) => { 5846 if (err != undefined) { 5847 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 5848 return; 5849 } 5850 console.info('Succeeded in getting entries'); 5851 console.info(`entries.length: ${entries.length}`); 5852 console.info(`entries[0]: ${entries[0]}`); 5853 }); 5854 } 5855 }); 5856} catch (e) { 5857 let error = e as BusinessError; 5858 console.error(`Failed to put batch.code is ${error.code},message is ${error.message}`); 5859} 5860``` 5861 5862### getEntries 5863 5864getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> 5865 5866Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. 5867> **NOTE** 5868> 5869> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 5870> For details about how to obtain **deviceId**, see [sync()](#sync). 5871 5872**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 5873 5874**Parameters** 5875 5876| Name | Type| Mandatory| Description | 5877| --------- | -------- | ---- | ------------------------ | 5878| deviceId | string | Yes | ID of the target device.| 5879| 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.| 5880 5881**Return value** 5882 5883| Type | Description | 5884| -------------------------------- | ------------------------------------------------- | 5885| Promise<[Entry](#entry)[]> | Promise used to return all the KV pairs that match the given condition.| 5886 5887**Error codes** 5888 5889For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5890 5891| ID| **Error Message** | 5892| ------------ | -------------------------------------- | 5893| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 5894| 15100003 | Database corrupted. | 5895| 15100005 | Database or result set already closed. | 5896 5897**Example** 5898 5899<!--code_no_check--> 5900```ts 5901import { BusinessError } from '@kit.BasicServicesKit'; 5902 5903try { 5904 let entries: distributedKVStore.Entry[] = []; 5905 for (let i = 0; i < 10; i++) { 5906 let key = 'batch_test_string_key'; 5907 let entry: distributedKVStore.Entry = { 5908 key: key + i, 5909 value: { 5910 type: distributedKVStore.ValueType.STRING, 5911 value: 'batch_test_string_value' 5912 } 5913 } 5914 entries.push(entry); 5915 } 5916 console.info(`entries: ${entries}`); 5917 kvStore.putBatch(entries).then(async () => { 5918 console.info('Succeeded in putting batch'); 5919 if (kvStore != null) { 5920 kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries: distributedKVStore.Entry[]) => { 5921 console.info('Succeeded in getting entries'); 5922 console.info(`entries.length: ${entries.length}`); 5923 console.info(`entries[0]: ${entries[0]}`); 5924 console.info(`entries[0].value: ${entries[0].value}`); 5925 console.info(`entries[0].value.value: ${entries[0].value.value}`); 5926 }).catch((err: BusinessError) => { 5927 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 5928 }); 5929 } 5930 }).catch((err: BusinessError) => { 5931 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 5932 }); 5933} catch (e) { 5934 let error = e as BusinessError; 5935 console.error(`Failed to put batch.code is ${error.code},message is ${error.message}`); 5936} 5937``` 5938 5939### getEntries 5940 5941getEntries(query: Query, callback: AsyncCallback<Entry[]>): void 5942 5943Obtains all KV pairs that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. 5944 5945**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 5946 5947**Parameters** 5948 5949| Name | Type | Mandatory| Description | 5950| -------- | -------------------------------------- | ---- | ----------------------------------------------------- | 5951| query | [Query](#query) | Yes | Key prefix to match. | 5952| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback used to return the KV pairs that match the specified **Query** object on the local device.| 5953 5954**Error codes** 5955 5956For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 5957 5958| ID| **Error Message** | 5959| ------------ | -------------------------------------- | 5960| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 5961| 15100003 | Database corrupted. | 5962| 15100005 | Database or result set already closed. | 5963 5964**Example** 5965 5966```ts 5967import { BusinessError } from '@kit.BasicServicesKit'; 5968 5969try { 5970 let arr = new Uint8Array([21, 31]); 5971 let entries: distributedKVStore.Entry[] = []; 5972 for (let i = 0; i < 10; i++) { 5973 let key = 'batch_test_bool_key'; 5974 let entry: distributedKVStore.Entry = { 5975 key: key + i, 5976 value: { 5977 type: distributedKVStore.ValueType.BYTE_ARRAY, 5978 value: arr 5979 } 5980 } 5981 entries.push(entry); 5982 } 5983 console.info(`entries: {entries}`); 5984 kvStore.putBatch(entries, async (err: BusinessError) => { 5985 console.info('Succeeded in putting Batch'); 5986 const query = new distributedKVStore.Query(); 5987 query.prefixKey("batch_test"); 5988 if (kvStore != null) { 5989 kvStore.getEntries(query, (err: BusinessError, entries: distributedKVStore.Entry[]) => { 5990 if (err != undefined) { 5991 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 5992 return; 5993 } 5994 console.info('Succeeded in getting Entries'); 5995 console.info(`entries.length: ${entries.length}`); 5996 console.info(`entries[0]: ${entries[0]}`); 5997 }); 5998 } 5999 }); 6000} catch (e) { 6001 let error = e as BusinessError; 6002 console.error(`Failed to get Entries.code is ${error.code},message is ${error.message}`); 6003} 6004``` 6005 6006### getEntries 6007 6008getEntries(query: Query): Promise<Entry[]> 6009 6010Obtains all KV pairs that match the specified **Query** object for this device. This API uses a promise to return the result. 6011 6012**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6013 6014**Parameters** 6015 6016| Name| Type | Mandatory| Description | 6017| ------ | -------------- | ---- | -------------- | 6018| query | [Query](#query) | Yes | **Query** object to match.| 6019 6020**Return value** 6021 6022| Type | Description | 6023| -------------------------------- | -------------------------------------------------------- | 6024| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified **Query** object on the local device.| 6025 6026**Error codes** 6027 6028For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6029 6030| ID| **Error Message** | 6031| ------------ | -------------------------------------- | 6032| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 6033| 15100003 | Database corrupted. | 6034| 15100005 | Database or result set already closed. | 6035 6036**Example** 6037 6038```ts 6039import { BusinessError } from '@kit.BasicServicesKit'; 6040 6041try { 6042 let arr = new Uint8Array([21, 31]); 6043 let entries: distributedKVStore.Entry[] = []; 6044 for (let i = 0; i < 10; i++) { 6045 let key = 'batch_test_bool_key'; 6046 let entry: distributedKVStore.Entry = { 6047 key: key + i, 6048 value: { 6049 type: distributedKVStore.ValueType.BYTE_ARRAY, 6050 value: arr 6051 } 6052 } 6053 entries.push(entry); 6054 } 6055 console.info(`entries: {entries}`); 6056 kvStore.putBatch(entries).then(async () => { 6057 console.info('Succeeded in putting Batch'); 6058 const query = new distributedKVStore.Query(); 6059 query.prefixKey("batch_test"); 6060 if (kvStore != null) { 6061 kvStore.getEntries(query).then((entries: distributedKVStore.Entry[]) => { 6062 console.info('Succeeded in getting Entries'); 6063 }).catch((err: BusinessError) => { 6064 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`); 6065 }); 6066 } 6067 }).catch((err: BusinessError) => { 6068 console.error(`Failed to get Entries.code is ${err.code},message is ${err.message}`) 6069 }); 6070 console.info('Succeeded in getting Entries'); 6071} catch (e) { 6072 let error = e as BusinessError; 6073 console.error(`Failed to get Entries.code is ${error.code},message is ${error.message}`); 6074} 6075``` 6076 6077### getEntries 6078 6079getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void 6080 6081Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 6082> **NOTE** 6083> 6084> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6085> For details about how to obtain **deviceId**, see [sync()](#sync). 6086 6087**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6088 6089**Parameters** 6090 6091| Name | Type | Mandatory| Description | 6092| -------- | -------------------------------------- | ---- | ------------------------------------------------------- | 6093| deviceId | string | Yes | ID of the target device. | 6094| query | [Query](#query) | Yes | **Query** object to match. | 6095| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback used to return the KV pairs that match the specified device ID and **Query** object.| 6096 6097**Error codes** 6098 6099For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6100 6101| ID| **Error Message** | 6102| ------------ | -------------------------------------- | 6103| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 6104| 15100003 | Database corrupted. | 6105| 15100005 | Database or result set already closed. | 6106 6107**Example** 6108 6109```ts 6110import { BusinessError } from '@kit.BasicServicesKit'; 6111 6112try { 6113 let arr = new Uint8Array([21, 31]); 6114 let entries: distributedKVStore.Entry[] = []; 6115 for (let i = 0; i < 10; i++) { 6116 let key = 'batch_test_bool_key'; 6117 let entry: distributedKVStore.Entry = { 6118 key: key + i, 6119 value: { 6120 type: distributedKVStore.ValueType.BYTE_ARRAY, 6121 value: arr 6122 } 6123 } 6124 entries.push(entry); 6125 } 6126 console.info(`entries: ${entries}`); 6127 kvStore.putBatch(entries, async (err: BusinessError) => { 6128 if (err != undefined) { 6129 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6130 return; 6131 } 6132 console.info('Succeeded in putting batch'); 6133 let query = new distributedKVStore.Query(); 6134 query.deviceId('localDeviceId'); 6135 query.prefixKey("batch_test"); 6136 if (kvStore != null) { 6137 kvStore.getEntries('localDeviceId', query, (err: BusinessError, entries: distributedKVStore.Entry[]) => { 6138 if (err != undefined) { 6139 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 6140 return; 6141 } 6142 console.info('Succeeded in getting entries'); 6143 console.info(`entries.length: ${entries.length}`); 6144 console.info(`entries[0]: ${entries[0]}`); 6145 }) 6146 } 6147 }); 6148 console.info('Succeeded in getting entries'); 6149} catch (e) { 6150 let error = e as BusinessError; 6151 console.error(`Failed to get entries.code is ${error.code},message is ${error.message}`); 6152} 6153``` 6154 6155### getEntries 6156 6157getEntries(deviceId: string, query: Query): Promise<Entry[]> 6158 6159Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. 6160> **NOTE** 6161> 6162> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6163> For details about how to obtain **deviceId**, see [sync()](#sync). 6164 6165**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6166 6167**Parameters** 6168 6169| Name | Type | Mandatory| Description | 6170| -------- | -------------- | ---- | -------------------- | 6171| deviceId | string | Yes | ID of the target device.| 6172| query | [Query](#query) | Yes | **Query** object to match. | 6173 6174**Return value** 6175 6176| Type | Description | 6177| -------------------------------- | ---------------------------------------------------------- | 6178| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs that match the specified device ID and **Query** object.| 6179 6180**Error codes** 6181 6182For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6183 6184| ID| **Error Message** | 6185| ------------ | -------------------------------------- | 6186| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 6187| 15100003 | Database corrupted. | 6188| 15100005 | Database or result set already closed. | 6189 6190**Example** 6191 6192<!--code_no_check--> 6193```ts 6194import { BusinessError } from '@kit.BasicServicesKit'; 6195 6196try { 6197 let arr = new Uint8Array([21, 31]); 6198 let entries: distributedKVStore.Entry[] = []; 6199 for (let i = 0; i < 10; i++) { 6200 let key = 'batch_test_bool_key'; 6201 let entry: distributedKVStore.Entry = { 6202 key: key + i, 6203 value: { 6204 type: distributedKVStore.ValueType.BYTE_ARRAY, 6205 value: arr 6206 } 6207 } 6208 entries.push(entry); 6209 } 6210 console.info(`entries: ${entries}`); 6211 kvStore.putBatch(entries).then(async () => { 6212 console.info('Succeeded in putting batch'); 6213 let query = new distributedKVStore.Query(); 6214 query.deviceId('localDeviceId'); 6215 query.prefixKey("batch_test"); 6216 if (kvStore != null) { 6217 kvStore.getEntries('localDeviceId', query).then((entries: distributedKVStore.Entry[]) => { 6218 console.info('Succeeded in getting entries'); 6219 }).catch((err: BusinessError) => { 6220 console.error(`Failed to get entries.code is ${err.code},message is ${err.message}`); 6221 }); 6222 } 6223 }).catch((err: BusinessError) => { 6224 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6225 }); 6226 console.info('Succeeded in getting entries'); 6227} catch (e) { 6228 let error = e as BusinessError; 6229 console.error(`Failed to get entries.code is ${error.code},message is ${error.message}`); 6230} 6231``` 6232 6233### getResultSet 6234 6235getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void 6236 6237Obtains a result set with the specified prefix for this device. This API uses an asynchronous callback to return the result. 6238 6239**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6240 6241**Parameters** 6242 6243| Name | Type | Mandatory| Description | 6244| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | 6245| 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.| 6246| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback used to return the result set with the specified prefix.| 6247 6248**Error codes** 6249 6250For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6251 6252| ID| **Error Message** | 6253| ------------ | -------------------------------------- | 6254| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 6255| 15100001 | Over max limits. | 6256| 15100003 | Database corrupted. | 6257| 15100005 | Database or result set already closed. | 6258 6259**Example** 6260 6261```ts 6262import { BusinessError } from '@kit.BasicServicesKit'; 6263 6264try { 6265 let resultSet: distributedKVStore.KVStoreResultSet; 6266 let entries: distributedKVStore.Entry[] = []; 6267 for (let i = 0; i < 10; i++) { 6268 let key = 'batch_test_string_key'; 6269 let entry: distributedKVStore.Entry = { 6270 key: key + i, 6271 value: { 6272 type: distributedKVStore.ValueType.STRING, 6273 value: 'batch_test_string_value' 6274 } 6275 } 6276 entries.push(entry); 6277 } 6278 kvStore.putBatch(entries, async (err: BusinessError) => { 6279 if (err != undefined) { 6280 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6281 return; 6282 } 6283 console.info('Succeeded in putting batch'); 6284 if (kvStore != null) { 6285 kvStore.getResultSet('batch_test_string_key', async (err: BusinessError, result: distributedKVStore.KVStoreResultSet) => { 6286 if (err != undefined) { 6287 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6288 return; 6289 } 6290 console.info('Succeeded in getting result set'); 6291 resultSet = result; 6292 if (kvStore != null) { 6293 kvStore.closeResultSet(resultSet, (err: BusinessError) => { 6294 if (err != undefined) { 6295 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 6296 return; 6297 } 6298 console.info('Succeeded in closing result set'); 6299 }) 6300 } 6301 }); 6302 } 6303 }); 6304} catch (e) { 6305 let error = e as BusinessError; 6306 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.message}`); 6307} 6308``` 6309 6310### getResultSet 6311 6312getResultSet(keyPrefix: string): Promise<KVStoreResultSet> 6313 6314Obtains a result set with the specified prefix for this device. This API uses a promise to return the result. 6315 6316**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6317 6318**Parameters** 6319 6320| Name | Type | Mandatory| Description | 6321| --------- | ------ | ---- | -------------------- | 6322| 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.| 6323 6324**Return value** 6325 6326| Type | Description | 6327| ---------------------------------------------------- | --------------------------------------- | 6328| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the result set with the specified prefix.| 6329 6330**Error codes** 6331 6332For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6333 6334| ID| **Error Message** | 6335| ------------ | -------------------------------------- | 6336| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 6337| 15100001 | Over max limits. | 6338| 15100003 | Database corrupted. | 6339| 15100005 | Database or result set already closed. | 6340 6341**Example** 6342 6343```ts 6344import { BusinessError } from '@kit.BasicServicesKit'; 6345 6346try { 6347 let resultSet: distributedKVStore.KVStoreResultSet; 6348 let entries: distributedKVStore.Entry[] = []; 6349 for (let i = 0; i < 10; i++) { 6350 let key = 'batch_test_string_key'; 6351 let entry: distributedKVStore.Entry = { 6352 key: key + i, 6353 value: { 6354 type: distributedKVStore.ValueType.STRING, 6355 value: 'batch_test_string_value' 6356 } 6357 } 6358 entries.push(entry); 6359 } 6360 kvStore.putBatch(entries).then(async () => { 6361 console.info('Succeeded in putting batch'); 6362 }).catch((err: BusinessError) => { 6363 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6364 }); 6365 kvStore.getResultSet('batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 6366 console.info('Succeeded in getting result set'); 6367 resultSet = result; 6368 if (kvStore != null) { 6369 kvStore.closeResultSet(resultSet).then(() => { 6370 console.info('Succeeded in closing result set'); 6371 }).catch((err: BusinessError) => { 6372 console.error(`Failed to close resultset.code is ${err.code},message is ${err.message}`); 6373 }); 6374 } 6375 }).catch((err: BusinessError) => { 6376 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6377 }); 6378} catch (e) { 6379 let error = e as BusinessError; 6380 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 6381} 6382``` 6383 6384### getResultSet 6385 6386getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void 6387 6388Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. 6389> **NOTE** 6390> 6391> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6392> For details about how to obtain **deviceId**, see [sync()](#sync). 6393 6394**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6395 6396**Parameters** 6397 6398| Name | Type | Mandatory| Description | 6399| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 6400| deviceId | string | Yes | ID of the target device. | 6401| 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.| 6402| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback used to return the **KVStoreResultSet** object obtained.| 6403 6404**Error codes** 6405 6406For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6407 6408| ID| **Error Message** | 6409| ------------ | -------------------------------------- | 6410| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 6411| 15100001 | Over max limits. | 6412| 15100003 | Database corrupted. | 6413| 15100005 | Database or result set already closed. | 6414 6415**Example** 6416 6417```ts 6418import { BusinessError } from '@kit.BasicServicesKit'; 6419 6420try { 6421 let resultSet: distributedKVStore.KVStoreResultSet; 6422 kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async (err: BusinessError, result: distributedKVStore.KVStoreResultSet) => { 6423 if (err != undefined) { 6424 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6425 return; 6426 } 6427 console.info('Succeeded in getting resultSet'); 6428 resultSet = result; 6429 if (kvStore != null) { 6430 kvStore.closeResultSet(resultSet, (err: BusinessError) => { 6431 if (err != undefined) { 6432 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6433 return; 6434 } 6435 console.info('Succeeded in closing resultSet'); 6436 }) 6437 } 6438 }); 6439} catch (e) { 6440 let error = e as BusinessError; 6441 console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`); 6442} 6443``` 6444 6445### getResultSet 6446 6447getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet> 6448 6449Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. 6450> **NOTE** 6451> 6452> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6453> For details about how to obtain **deviceId**, see [sync()](#sync). 6454 6455**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6456 6457**Parameters** 6458 6459| Name | Type| Mandatory| Description | 6460| --------- | -------- | ---- | ------------------------ | 6461| deviceId | string | Yes | ID of the target device.| 6462| 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.| 6463 6464**Return value** 6465 6466| Type | Description | 6467| ------------------------------------------------------ | ------------------------------------------------------------ | 6468| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| 6469 6470**Error codes** 6471 6472For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6473 6474| ID| **Error Message** | 6475| ------------ | -------------------------------------- | 6476| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 6477| 15100001 | Over max limits. | 6478| 15100003 | Database corrupted. | 6479| 15100005 | Database or result set already closed. | 6480 6481**Example** 6482 6483<!--code_no_check--> 6484```ts 6485import { BusinessError } from '@kit.BasicServicesKit'; 6486 6487try { 6488 let resultSet: distributedKVStore.KVStoreResultSet; 6489 kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result: distributedKVStore.KVStoreResultSet) => { 6490 console.info('Succeeded in getting resultSet'); 6491 resultSet = result; 6492 if (kvStore != null) { 6493 kvStore.closeResultSet(resultSet).then(() => { 6494 console.info('Succeeded in closing resultSet'); 6495 }).catch((err: BusinessError) => { 6496 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6497 }); 6498 } 6499 }).catch((err: BusinessError) => { 6500 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6501 }); 6502} catch (e) { 6503 let error = e as BusinessError; 6504 console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`); 6505} 6506``` 6507 6508### getResultSet 6509 6510getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreResultSet>): void 6511 6512Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 6513> **NOTE** 6514> 6515> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6516> For details about how to obtain **deviceId**, see [sync()](#sync). 6517 6518**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6519 6520**Parameters** 6521 6522| Name | Type | Mandatory| Description | 6523| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 6524| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | 6525| query | [Query](#query) | Yes | **Query** object to match. | 6526| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback used to return the **KVStoreResultSet** object that matches the specified device ID and **Query** object.| 6527 6528**Error codes** 6529 6530For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6531 6532| ID| **Error Message** | 6533| ------------ | -------------------------------------- | 6534| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 6535| 15100001 | Over max limits. | 6536| 15100003 | Database corrupted. | 6537| 15100005 | Database or result set already closed. | 6538 6539**Example** 6540 6541```ts 6542import { BusinessError } from '@kit.BasicServicesKit'; 6543 6544try { 6545 let resultSet: distributedKVStore.KVStoreResultSet; 6546 let entries: distributedKVStore.Entry[] = []; 6547 for (let i = 0; i < 10; i++) { 6548 let key = 'batch_test_string_key'; 6549 let entry: distributedKVStore.Entry = { 6550 key: key + i, 6551 value: { 6552 type: distributedKVStore.ValueType.STRING, 6553 value: 'batch_test_string_value' 6554 } 6555 } 6556 entries.push(entry); 6557 } 6558 kvStore.putBatch(entries, async (err: BusinessError) => { 6559 if (err != undefined) { 6560 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6561 return; 6562 } 6563 console.info('Succeeded in putting batch'); 6564 const query = new distributedKVStore.Query(); 6565 query.prefixKey("batch_test"); 6566 if (kvStore != null) { 6567 kvStore.getResultSet('localDeviceId', query, async (err: BusinessError, result: distributedKVStore.KVStoreResultSet) => { 6568 if (err != undefined) { 6569 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6570 return; 6571 } 6572 console.info('Succeeded in getting resultSet'); 6573 resultSet = result; 6574 if (kvStore != null) { 6575 kvStore.closeResultSet(resultSet, (err: BusinessError) => { 6576 if (err != undefined) { 6577 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6578 return; 6579 } 6580 console.info('Succeeded in closing resultSet'); 6581 }) 6582 } 6583 }); 6584 } 6585 }); 6586} catch (e) { 6587 let error = e as BusinessError; 6588 console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`); 6589} 6590``` 6591 6592### getResultSet 6593 6594getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> 6595 6596Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. 6597> **NOTE** 6598> 6599> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6600> For details about how to obtain **deviceId**, see [sync()](#sync). 6601 6602**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6603 6604**Parameters** 6605 6606| Name | Type | Mandatory| Description | 6607| -------- | -------------- | ---- | ---------------------------------- | 6608| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| 6609| query | [Query](#query) | Yes | **Query** object to match. | 6610 6611**Return value** 6612 6613| Type | Description | 6614| ------------------------------------------------------ | ------------------------------------------------------------ | 6615| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object that matches the specified device ID and **Query** object.| 6616 6617**Error codes** 6618 6619For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6620 6621| ID| **Error Message** | 6622| ------------ | -------------------------------------- | 6623| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 6624| 15100001 | Over max limits. | 6625| 15100003 | Database corrupted. | 6626| 15100005 | Database or result set already closed. | 6627 6628**Example** 6629 6630<!--code_no_check--> 6631```ts 6632import { BusinessError } from '@kit.BasicServicesKit'; 6633 6634try { 6635 let resultSet: distributedKVStore.KVStoreResultSet; 6636 let entries: distributedKVStore.Entry[] = []; 6637 for (let i = 0; i < 10; i++) { 6638 let key = 'batch_test_string_key'; 6639 let entry: distributedKVStore.Entry = { 6640 key: key + i, 6641 value: { 6642 type: distributedKVStore.ValueType.STRING, 6643 value: 'batch_test_string_value' 6644 } 6645 } 6646 entries.push(entry); 6647 } 6648 kvStore.putBatch(entries).then(async () => { 6649 console.info('Succeeded in putting batch'); 6650 }).catch((err: BusinessError) => { 6651 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6652 }); 6653 const query = new distributedKVStore.Query(); 6654 query.prefixKey("batch_test"); 6655 if (kvStore != null) { 6656 kvStore.getResultSet('localDeviceId', query).then((result: distributedKVStore.KVStoreResultSet) => { 6657 console.info('Succeeded in getting resultSet'); 6658 resultSet = result; 6659 if (kvStore != null) { 6660 kvStore.closeResultSet(resultSet).then(() => { 6661 console.info('Succeeded in closing resultSet'); 6662 }).catch((err: BusinessError) => { 6663 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6664 }); 6665 } 6666 }).catch((err: BusinessError) => { 6667 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6668 }); 6669 } 6670 query.deviceId('localDeviceId'); 6671 console.info("GetResultSet " + query.getSqlLike()); 6672 6673} catch (e) { 6674 let error = e as BusinessError; 6675 console.error(`Failed to get resultSet.code is ${error.code},message is ${error.message}`); 6676} 6677``` 6678 6679### getResultSet 6680 6681getResultSet(query: Query): Promise<KVStoreResultSet> 6682 6683Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses a promise to return the result. 6684 6685**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6686 6687**Parameters** 6688 6689| Name| Type | Mandatory| Description | 6690| ------ | -------------- | ---- | -------------- | 6691| query | [Query](#query) | Yes | **Query** object to match.| 6692 6693**Return value** 6694 6695| Type | Description | 6696| ---------------------------------------------------- | ------------------------------------------------------------ | 6697| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| 6698 6699**Error codes** 6700 6701For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6702 6703| ID| **Error Message** | 6704| ------------ | -------------------------------------- | 6705| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 6706| 15100001 | Over max limits. | 6707| 15100003 | Database corrupted. | 6708| 15100005 | Database or result set already closed. | 6709 6710**Example** 6711 6712```ts 6713import { BusinessError } from '@kit.BasicServicesKit'; 6714 6715try { 6716 let resultSet: distributedKVStore.KVStoreResultSet; 6717 let entries: distributedKVStore.Entry[] = []; 6718 for (let i = 0; i < 10; i++) { 6719 let key = 'batch_test_string_key'; 6720 let entry: distributedKVStore.Entry = { 6721 key: key + i, 6722 value: { 6723 type: distributedKVStore.ValueType.STRING, 6724 value: 'batch_test_string_value' 6725 } 6726 } 6727 entries.push(entry); 6728 } 6729 kvStore.putBatch(entries).then(async () => { 6730 console.info('Succeeded in putting batch'); 6731 }).catch((err: BusinessError) => { 6732 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6733 }); 6734 const query = new distributedKVStore.Query(); 6735 query.prefixKey("batch_test"); 6736 kvStore.getResultSet(query).then((result: distributedKVStore.KVStoreResultSet) => { 6737 console.info('Succeeded in getting result set'); 6738 resultSet = result; 6739 }).catch((err: BusinessError) => { 6740 console.error(`Failed to get resultset.code is ${err.code},message is ${err.message}`); 6741 }); 6742} catch (e) { 6743 let error = e as BusinessError; 6744 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 6745} 6746``` 6747 6748### getResultSet 6749 6750getResultSet(query: Query, callback:AsyncCallback<KVStoreResultSet>): void 6751 6752Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses an asynchronous callback to return the result. 6753> **NOTE** 6754> 6755> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6756> For details about how to obtain **deviceId**, see [sync()](#sync). 6757 6758**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6759 6760**Parameters** 6761 6762| Name | Type | Mandatory| Description | 6763| -------- | -------------- | ---- | ---------------------------------- | 6764| query | [Query](#query) | Yes | **Query** object to match. | 6765| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback used to return the **KVStoreResultSet** object obtained. | 6766 6767 6768**Error codes** 6769 6770For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6771 6772| ID| **Error Message** | 6773| ------------ | -------------------------------------- | 6774| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types.| 6775| 15100001 | Over max limits. | 6776| 15100003 | Database corrupted. | 6777| 15100005 | Database or result set already closed. | 6778 6779**Example** 6780 6781```ts 6782import { BusinessError } from '@kit.BasicServicesKit'; 6783 6784try { 6785 let resultSet: distributedKVStore.KVStoreResultSet; 6786 let entries: distributedKVStore.Entry[] = []; 6787 for (let i = 0; i < 10; i++) { 6788 let key = 'batch_test_string_key'; 6789 let entry: distributedKVStore.Entry = { 6790 key: key + i, 6791 value: { 6792 type: distributedKVStore.ValueType.STRING, 6793 value: 'batch_test_string_value' 6794 } 6795 } 6796 entries.push(entry); 6797 } 6798 kvStore.putBatch(entries, async (err: BusinessError) => { 6799 if (err != undefined) { 6800 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6801 return; 6802 } 6803 console.info('Succeeded in putting batch'); 6804 const query = new distributedKVStore.Query(); 6805 query.prefixKey("batch_test"); 6806 if (kvStore != null) { 6807 kvStore.getResultSet(query, async (err: BusinessError, result: distributedKVStore.KVStoreResultSet) => { 6808 if (err != undefined) { 6809 console.error(`Failed to get resultSet.code is ${err.code},message is ${err.message}`); 6810 return; 6811 } 6812 console.info('Succeeded in getting resultSet'); 6813 resultSet = result; 6814 if (kvStore != null) { 6815 kvStore.closeResultSet(resultSet, (err: BusinessError) => { 6816 if (err != undefined) { 6817 console.error(`Failed to close resultSet.code is ${err.code},message is ${err.message}`); 6818 return; 6819 } 6820 console.info('Succeeded in closing resultSet'); 6821 }) 6822 } 6823 }); 6824 } 6825 }); 6826} catch (e) { 6827 let error = e as BusinessError; 6828 console.error(`Failed to get resultSet`); 6829} 6830``` 6831 6832### getResultSize 6833 6834getResultSize(query: Query, callback: AsyncCallback<number>): void 6835 6836Obtains the number of results that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. 6837 6838**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6839 6840**Parameters** 6841 6842| Name | Type | Mandatory| Description | 6843| -------- | --------------------------- | ---- | ------------------------------------------------- | 6844| query | [Query](#query) | Yes | **Query** object to match. | 6845| callback | AsyncCallback<number> | Yes | Callback used to return the number of results obtained.| 6846 6847**Error codes** 6848 6849For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6850 6851| ID| **Error Message** | 6852| ------------ | -------------------------------------- | 6853| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 6854| 15100003 | Database corrupted. | 6855| 15100005 | Database or result set already closed. | 6856 6857**Example** 6858 6859```ts 6860import { BusinessError } from '@kit.BasicServicesKit'; 6861 6862try { 6863 let entries: distributedKVStore.Entry[] = []; 6864 for (let i = 0; i < 10; i++) { 6865 let key = 'batch_test_string_key'; 6866 let entry: distributedKVStore.Entry = { 6867 key: key + i, 6868 value: { 6869 type: distributedKVStore.ValueType.STRING, 6870 value: 'batch_test_string_value' 6871 } 6872 } 6873 entries.push(entry); 6874 } 6875 kvStore.putBatch(entries, async (err: BusinessError) => { 6876 console.info('Succeeded in putting batch'); 6877 const query = new distributedKVStore.Query(); 6878 query.prefixKey("batch_test"); 6879 if (kvStore != null) { 6880 kvStore.getResultSize(query, async (err: BusinessError, resultSize: number) => { 6881 if (err != undefined) { 6882 console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); 6883 return; 6884 } 6885 console.info('Succeeded in getting result set size'); 6886 }); 6887 } 6888 }); 6889} catch (e) { 6890 let error = e as BusinessError; 6891 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 6892} 6893``` 6894 6895### getResultSize 6896 6897getResultSize(query: Query): Promise<number> 6898 6899Obtains the number of results that match the specified **Query** object for this device. This API uses a promise to return the result. 6900 6901**System capability**: SystemCapability.DistributedDataManager.KVStore.Core 6902 6903**Parameters** 6904 6905| Name| Type | Mandatory| Description | 6906| ------ | -------------- | ---- | -------------- | 6907| query | [Query](#query) | Yes | **Query** object to match.| 6908 6909**Return value** 6910 6911| Type | Description | 6912| --------------------- | ---------------------------------------------------- | 6913| Promise<number> | Promise used to return the number of results obtained.| 6914 6915**Error codes** 6916 6917For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6918 6919| ID| **Error Message** | 6920| ------------ | -------------------------------------- | 6921| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 6922| 15100003 | Database corrupted. | 6923| 15100005 | Database or result set already closed. | 6924 6925**Example** 6926 6927```ts 6928import { BusinessError } from '@kit.BasicServicesKit'; 6929 6930try { 6931 let entries: distributedKVStore.Entry[] = []; 6932 for (let i = 0; i < 10; i++) { 6933 let key = 'batch_test_string_key'; 6934 let entry: distributedKVStore.Entry = { 6935 key: key + i, 6936 value: { 6937 type: distributedKVStore.ValueType.STRING, 6938 value: 'batch_test_string_value' 6939 } 6940 } 6941 entries.push(entry); 6942 } 6943 kvStore.putBatch(entries).then(async () => { 6944 console.info('Succeeded in putting batch'); 6945 }).catch((err: BusinessError) => { 6946 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 6947 }); 6948 const query = new distributedKVStore.Query(); 6949 query.prefixKey("batch_test"); 6950 kvStore.getResultSize(query).then((resultSize: number) => { 6951 console.info('Succeeded in getting result set size'); 6952 }).catch((err: BusinessError) => { 6953 console.error(`Failed to get result size.code is ${err.code},message is ${err.message}`); 6954 }); 6955} catch (e) { 6956 let error = e as BusinessError; 6957 console.error(`An unexpected error occurred.code is ${error.code},message is ${error.code}`); 6958} 6959``` 6960 6961### getResultSize 6962 6963getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; 6964 6965Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. 6966> **NOTE** 6967> 6968> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 6969> For details about how to obtain **deviceId**, see [sync()](#sync). 6970 6971**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 6972 6973**Parameters** 6974 6975| Name | Type | Mandatory| Description | 6976| -------- | --------------------------- | ---- | --------------------------------------------------- | 6977| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | 6978| query | [Query](#query) | Yes | **Query** object to match. | 6979| callback | AsyncCallback<number> | Yes | Callback used to return the number of results obtained.| 6980 6981**Error codes** 6982 6983For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 6984 6985| ID| **Error Message** | 6986| ------------ | -------------------------------------- | 6987| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 6988| 15100003 | Database corrupted. | 6989| 15100005 | Database or result set already closed. | 6990 6991**Example** 6992 6993```ts 6994import { BusinessError } from '@kit.BasicServicesKit'; 6995 6996try { 6997 let entries: distributedKVStore.Entry[] = []; 6998 for (let i = 0; i < 10; i++) { 6999 let key = 'batch_test_string_key'; 7000 let entry: distributedKVStore.Entry = { 7001 key: key + i, 7002 value: { 7003 type: distributedKVStore.ValueType.STRING, 7004 value: 'batch_test_string_value' 7005 } 7006 } 7007 entries.push(entry); 7008 } 7009 kvStore.putBatch(entries, async (err: BusinessError) => { 7010 if (err != undefined) { 7011 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 7012 return; 7013 } 7014 console.info('Succeeded in putting batch'); 7015 const query = new distributedKVStore.Query(); 7016 query.prefixKey("batch_test"); 7017 if (kvStore != null) { 7018 kvStore.getResultSize('localDeviceId', query, async (err: BusinessError, resultSize: number) => { 7019 if (err != undefined) { 7020 console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`); 7021 return; 7022 } 7023 console.info('Succeeded in getting resultSize'); 7024 }); 7025 } 7026 }); 7027} catch (e) { 7028 let error = e as BusinessError; 7029 console.error(`Failed to get resultSize.code is ${error.code},message is ${error.message}`); 7030} 7031``` 7032 7033### getResultSize 7034 7035getResultSize(deviceId: string, query: Query): Promise<number> 7036 7037Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. 7038> **NOTE** 7039> 7040> **deviceId** can be obtained by [deviceManager.getAvailableDeviceListSync](../apis-distributedservice-kit/js-apis-distributedDeviceManager.md#getavailabledevicelistsync). 7041> For details about how to obtain **deviceId**, see [sync()](#sync). 7042 7043**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore 7044 7045**Parameters** 7046 7047| Name | Type | Mandatory| Description | 7048| -------- | -------------- | ---- | ---------------------------------- | 7049| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| 7050| query | [Query](#query) | Yes | **Query** object to match. | 7051 7052**Return value** 7053 7054| Type | Description | 7055| --------------------- | ------------------------------------------------------ | 7056| Promise<number> | Promise used to return the number of results obtained.| 7057 7058**Error codes** 7059 7060For details about the error codes, see [Distributed KV Store Error Codes](errorcode-distributedKVStore.md) and [Universal Error Codes](../errorcode-universal.md). 7061 7062| ID| **Error Message** | 7063| ------------ | -------------------------------------- | 7064| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | 7065| 15100003 | Database corrupted. | 7066| 15100005 | Database or result set already closed. | 7067 7068**Example** 7069 7070```ts 7071import { BusinessError } from '@kit.BasicServicesKit'; 7072 7073try { 7074 let entries: distributedKVStore.Entry[] = []; 7075 for (let i = 0; i < 10; i++) { 7076 let key = 'batch_test_string_key'; 7077 let entry: distributedKVStore.Entry = { 7078 key: key + i, 7079 value: { 7080 type: distributedKVStore.ValueType.STRING, 7081 value: 'batch_test_string_value' 7082 } 7083 } 7084 entries.push(entry); 7085 } 7086 kvStore.putBatch(entries).then(async () => { 7087 console.info('Succeeded in putting batch'); 7088 }).catch((err: BusinessError) => { 7089 console.error(`Failed to put batch.code is ${err.code},message is ${err.message}`); 7090 }); 7091 let query = new distributedKVStore.Query(); 7092 query.prefixKey("batch_test"); 7093 kvStore.getResultSize('localDeviceId', query).then((resultSize: number) => { 7094 console.info('Succeeded in getting resultSize'); 7095 }).catch((err: BusinessError) => { 7096 console.error(`Failed to get resultSize.code is ${err.code},message is ${err.message}`); 7097 }); 7098} catch (e) { 7099 let error = e as BusinessError; 7100 console.error(`Failed to get resultSize.code is ${error.code},message is ${error.message}`); 7101} 7102``` 7103