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