1# @ohos.data.dataShare (DataShare) (System API) 2 3The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. 4 5> **NOTE** 6> 7> - 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. 8> 9> - The APIs provided by this module are system APIs. 10> 11> - The APIs of this module can be used only in the stage model. 12> 13> - The callback in **on('rdbDataChange')** cannot transfer data larger than 200 KB in size. 14 15 16## Modules to Import 17 18```ts 19import { dataShare } from '@kit.ArkData'; 20``` 21 22## dataShare.createDataShareHelper 23 24createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void 25 26Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result. 27 28> **NOTE** 29> 30> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 31 32**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 33 34**Parameters** 35 36| Name | Type | Mandatory| Description | 37| -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | 38| context | [Context](../apis-ability-kit/js-apis-inner-application-context.md#context) | Yes | Context of the application. | 39| uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect. | 40| callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.| 41 42**Error codes** 43 44For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 45 46| ID| Error Message | 47| -------- | ---------------------------------------------------- | 48| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 49| 15700010 | The DataShareHelper is not initialized successfully. | 50 51**Example** 52 53```ts 54import { BusinessError } from '@kit.BasicServicesKit' 55import { UIAbility } from '@kit.AbilityKit'; 56 57let uri = ("datashare:///com.samples.datasharetest.DataShare"); 58let dataShareHelper: dataShare.DataShareHelper | undefined = undefined; 59let context = getContext(UIAbility); 60try { 61 dataShare.createDataShareHelper(context, uri, (err:BusinessError, data:dataShare.DataShareHelper) => { 62 if (err !== undefined) { 63 console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); 64 return; 65 } 66 console.info("createDataShareHelper succeed, data : " + data); 67 dataShareHelper = data; 68 }); 69} catch (err) { 70 let code = (err as BusinessError).code; 71 let message = (err as BusinessError).message; 72 console.error(`createDataShareHelper error: code: ${code}, message: ${message} `); 73}; 74``` 75 76## dataShare.createDataShareHelper<sup>10+</sup> 77createDataShareHelper(context: Context, uri: string, options: DataShareHelperOptions, callback: AsyncCallback<DataShareHelper>): void 78 79Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result. 80 81> **NOTE** 82> 83> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 84 85**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 86 87 88| Name | Type | Mandatory| Description | 89| -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | 90| context | [Context](../apis-ability-kit/js-apis-inner-application-context.md#context) | Yes | Context of the application. | 91| uri | string | Yes | URI of the server application to connect. | 92| options | [DataShareHelperOptions](#datasharehelperoptions10)| Yes | Whether [DataShareHelper](#datasharehelper) is in proxy mode and the waiting time for starting the data provider process in non-silent access mode.<br>If this parameter is not set, [DataShareHelper](#datasharehelper) is not in proxy mode and the waiting time for starting the data provider process in non-silent access mode is 2 seconds.<br>If the URI starts with **datashareproxy**, the **isProxy** parameter in **options** must be set. Otherwise, **DataShareHelper** will fail to be created and an error will be returned.| 93| callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.| 94 95**Error codes** 96 97For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 98 99| ID| Error Message | 100| -------- | ---------------------------------------------------- | 101| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 102| 15700010 | The DataShareHelper is not initialized successfully. | 103 104**Example** 105 106```ts 107import { BusinessError } from '@kit.BasicServicesKit' 108import { UIAbility } from '@kit.AbilityKit'; 109 110let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 111let dataShareHelper: dataShare.DataShareHelper | undefined = undefined; 112let context = getContext(UIAbility); 113try { 114 dataShare.createDataShareHelper(context, uri, {isProxy : true}, (err:BusinessError, data:dataShare.DataShareHelper) => { 115 if (err !== undefined) { 116 console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); 117 return; 118 } 119 console.info("createDataShareHelper succeed, data : " + data); 120 dataShareHelper = data; 121 }); 122} catch (err) { 123 let code = (err as BusinessError).code; 124 let message = (err as BusinessError).message; 125 console.error(`createDataShareHelper error: code: ${code}, message: ${message} `); 126}; 127``` 128## dataShare.createDataShareHelper 129 130createDataShareHelper(context: Context, uri: string, options?: DataShareHelperOptions): Promise<DataShareHelper> 131 132Creates a **DataShareHelper** instance. This API uses a promise to return the result. 133 134> **NOTE** 135> 136> For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). 137 138**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 139 140**Parameters** 141 142| Name | Type | Mandatory| Description | 143| ------- | ------------------------------------------------- | ---- | ------------------------------ | 144| context | [Context](../apis-ability-kit/js-apis-inner-application-context.md#context) | Yes | Context of the application. | 145| uri | string | Yes | URI of the server application to connect.| 146| options<sup>10+</sup> | [DataShareHelperOptions](#datasharehelperoptions10) | No| Optional configuration of the **DataShareHelper** instance. It specifies whether [DataShareHelper](#datasharehelper) is in proxy mode and the waiting time for starting the data provider process in non-silent access mode.<br>If this parameter is not set, [DataShareHelper](#datasharehelper) is not in proxy mode and the waiting time for starting the data provider process in non-silent access mode is 2 seconds.<br>If the URI starts with **datashareproxy**, the **isProxy** parameter in **options** must be set. Otherwise, **DataShareHelper** will fail to be created and an error will be returned. | 147 148**Return value** 149 150| Type | Description | 151| -------------------------------------------------- | -------------------------------------- | 152| Promise<[DataShareHelper](#datasharehelper)> | Promise used to return the **DataShareHelper** instance created.| 153 154**Error codes** 155 156For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 157 158| ID| Error Message | 159| -------- | ---------------------------------------------------- | 160| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 161| 15700010 | The DataShareHelper is not initialized successfully. | 162 163**Example** 164 165```ts 166import { BusinessError } from '@kit.BasicServicesKit' 167import { UIAbility } from '@kit.AbilityKit'; 168 169let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 170let dataShareHelper: dataShare.DataShareHelper | undefined = undefined; 171let context = getContext(UIAbility); 172try { 173 dataShare.createDataShareHelper(context, uri, {isProxy : true}).then((data: dataShare.DataShareHelper) => { 174 console.info("createDataShareHelper succeed, data : " + data); 175 dataShareHelper = data; 176 }). catch((err: BusinessError) => { 177 console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); 178 }); 179} catch (err) { 180 let code = (err as BusinessError).code; 181 let message = (err as BusinessError).message; 182 console.error(`createDataShareHelper error: code: ${code}, message: ${message} `); 183}; 184``` 185 186## dataShare.enableSilentProxy<sup>11+</sup> 187 188enableSilentProxy(context: Context, uri?: string): Promise<void> 189 190Enables silent access. This API uses a promise to return the result. 191 192Observe the following when using this API: 193 - The data provider calls this API to enable silent access. 194 - Whether silent access is enabled is determined based on the return value of this API and the [isSilentProxyEnable](../../database/share-data-by-datashareextensionability.md) field in the **data_share_config.json** file together. 195 - If silent access is enabled for a URI using this API, silent access takes effect when the related **datashareHelper** API is called. Otherwise, the setting of **isSilentProxyEnable** in the **data_share_config.json** file is used to determine whether to enable silent access. 196 197**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 198 199**Parameters** 200 201| Name | Type | Mandatory| Description | 202| ------- | ------------------------------------------------------- | ---- |----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 203| context | [Context](../apis-ability-kit/js-apis-inner-application-context.md#context) | Yes | Context of the application. | 204| uri | string | No | URI of the data, for which silent access is to be enabled.<br>Global setting: If **uri** is **undefined** or **null** or is not specified, all the previous settings will be cleared and silent access will be enabled globally for the data provider.<br>URI-specific setting: If a URI is specified, silent access to the specified URI will be enabled.<br>When datashareHelper APIs are called, the URI-specific setting is preferentially applied. If no match is found, the global setting is applied.<br>URI format: **datashare:///{bundleName}/{moduleName}/{storeName}/{tableName}**| 205 206**Return value** 207 208| Type | Description | 209| -------------------------------------------------- | -------------------------------------- | 210| Promise<void> | returns no value.| 211 212**Error codes** 213 214For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 215 216| ID| Error Message | 217| -------- | ---------------------------------------------------- | 218| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 219| 15700011 | The URI is not exist. | 220 221**Example** 222 223```ts 224import { BusinessError } from '@kit.BasicServicesKit' 225import { UIAbility } from '@kit.AbilityKit'; 226 227let uri = ("datashare:///com.acts.datasharetest/entry/DB00/TBL00?Proxy=true"); 228let context = getContext(UIAbility); 229dataShare.enableSilentProxy(context, uri).then(() => { 230 console.info("enableSilentProxy succeed"); 231}). catch((err: BusinessError) => { 232 console.error(`enableSilentProxy error: code: ${err.code}, message: ${err.message} `); 233}); 234``` 235 236## dataShare.disableSilentProxy<sup>11+</sup> 237 238disableSilentProxy(context: Context, uri?: string): Promise<void> 239 240Disables silent access. This API uses a promise to return the result. 241 242Observe the following when using this API: 243 - The data provider calls this API to disable silent access. 244 - Whether silent access is disabled is determined based on the return value of this API and the [isSilentProxyEnable](../../database/share-data-by-datashareextensionability.md) field in the **data_share_config.json** file together. 245 - If silent access is disabled for a URI using this API, the setting takes effect when the related **datashareHelper** API is called. Otherwise, the setting of **isSilentProxyEnable** in the **data_share_config.json** file is used to determine whether to disable silent access. 246 247**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 248 249**Parameters** 250 251| Name | Type | Mandatory| Description | 252| ------- | ------------------------------------------------------- | ---- |--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 253| context | [Context](../apis-ability-kit/js-apis-inner-application-context.md#context) | Yes | Context of the application. | 254| uri | string | No | URI of the data, for which silent access is to be disabled.<br>Global setting: If **uri** is **undefined** or **null** or is not specified, all the previous settings will be cleared and silent access will be disabled globally for the data provider.<br>URI-specific setting: If a URI is specified, silent access to the specified URI will be disabled.<br>When datashareHelper APIs are called, the URI-specific setting is preferentially applied. If no match is found, the global setting is applied.<br>URI format: **datashare:///{bundleName}/{moduleName}/{storeName}/{tableName}**| 255 256**Return value** 257 258| Type | Description | 259| -------------------------------------------------- | -------------------------------------- | 260| Promise<void> | returns no value.| 261 262**Error codes** 263 264For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 265 266| ID| Error Message | 267| -------- | ---------------------------------------------------- | 268| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 269| 15700011 | The URI does not exist. | 270 271**Example** 272 273```ts 274import { BusinessError } from '@kit.BasicServicesKit' 275import { UIAbility } from '@kit.AbilityKit'; 276 277let uri = ("datashare:///com.acts.datasharetest/entry/DB00/TBL00?Proxy=true"); 278let context = getContext(UIAbility); 279dataShare.disableSilentProxy(context, uri).then(() => { 280 console.info("disableSilentProxy succeed"); 281}). catch((err: BusinessError) => { 282 console.error(`disableSilentProxy error: code: ${err.code}, message: ${err.message} `); 283}); 284``` 285 286## DataShareHelperOptions<sup>10+</sup> 287 288Represents the optional parameters of [DataShareHelper](#datasharehelper). 289 290**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 291 292| Name| Type| Mandatory| Description| 293| -------- | -------- | -------- | -------- | 294| isProxy | boolean | No| Whether the [DataShareHelper](#datasharehelper) is in proxy mode.<br>The default value is **false**.<br>If the value is **true**, the [DataShareHelper](#datasharehelper) to be created is in proxy mode, and all operations will not open the data provider application unless the database does not exist. If the database does not exist, [createDataShareHelper](#datasharecreatedatasharehelper10) will start the data provider to create a database.| 295| waitTime<sup>16+</sup> | number | No| Waiting time for starting the data provider process, in seconds.<br>The default value is **2**.| 296 297## TemplateId<sup>10+</sup> 298 299Defines the **TemplateId** struct. **TemplateId** is generated by [**addTemplate**](#addtemplate10) to identify a template. 300 301**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 302 303| Name| Type| Mandatory| Description| 304| -------- | -------- | -------- | -------- | 305| subscriberId | string | Yes| ID of the subscriber who handles the callback. The value must the same as the **subscriberId** in [**addTemplate**](#addtemplate10). The ID of each subscriber must be unique.| 306| bundleNameOfOwner | string | Yes| Bundle name of the template owner. The value must be the same as the **bundleName** in [**addTemplate**](#addtemplate10).| 307 308## PublishedItem<sup>10+</sup> 309 310Defines the data to publish. 311 312**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 313 314| Name| Type| Mandatory| Description| 315| -------- | -------- | -------- | -------- | 316| key | string | Yes| Key of the data to publish.| 317| data | string \| ArrayBuffer | Yes| Data to publish. If the data to publish exceeds 20 KB, you are advised to use the data in ArrayBuffer format.| 318| subscriberId | string | Yes| Subscriber ID.| 319 320## RdbDataChangeNode<sup>10+</sup> 321 322Represents the RDB data change result. The data returned by the callback is not larger than 200 KB in size. 323 324**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 325 326| Name| Type| Mandatory| Description| 327| -------- | -------- | -------- | -------- | 328| uri | string | Yes| URI of the callback.| 329| templateId | [TemplateId](#templateid10) | Yes| ID of the template that triggers the callback.| 330| data | Array<string> | Yes| Data of the callback. If an error occurs during callback data processing, the callback will not be triggered.| 331 332## PublishedDataChangeNode<sup>10+</sup> 333 334Defines the subscription/unsubscription result of the changes in the published data. 335 336**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 337 338| Name| Type| Mandatory| Description| 339| -------- | -------- | -------- | -------- | 340| bundleName | string | Yes| Bundle name of the callback.| 341| data | Array<[PublishedItem](#publisheditem10)> | Yes| Data of the callback.| 342 343## Template<sup>10+</sup> 344 345Defines the struct of the template used in a subscription. 346 347**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 348 349| Name| Type| Mandatory| Description| 350| -------- | -------- | -------- | -------- | 351| predicates | Record<string, string> | Yes| Predicates to use. When [**on**](#onrdbdatachange10) is called, the predicates are used to generate data. This parameter applies only to RDB data storage. | 352| scheduler | string | Yes| Template scheduler SQL, which is embedded with a custom function. Currently, the **remindTimer** function is embedded. The **remindTimer** triggers a subscription-based update in specified scenarios.<br>The scheduler SQL statement is triggered when:<br>1. The subscribed data is modified.<br>2. The first subscription is added to the corresponding database.| 353| update<sup>14+<sup> | string | No| Update SQL statement of a specified template. The default value is an empty string. When [on](#onrdbdatachange10) is called, the **update** parameter is used to update data. This parameter applies only to RDB data storage. | 354 355## OperationResult<sup>10+</sup> 356 357Defines the result of the operation for subscribing to or unsubscribing from the data changes or published data. 358 359**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 360 361| Name| Type| Mandatory| Description| 362| -------- | -------- | ----- | -------- | 363| key | string | Yes| Key of the operation result.| 364| result | number | Yes| Operation result. If the operation is successful, **0** is returned; otherwise, an error code is returned. | 365## UpdateOperation<sup>12+</sup> 366 367Represents the batch update operation information. 368 369**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 370 371| Name | Type | Mandatory| Description | 372| ---------- | ------------------------------------------------------------ | ---- | -------------- | 373| values | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to be updated, which| 374| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions for deleting the data. | 375 376## ChangeType<sup>12+</sup> 377 378Enumerates the data change types. 379 380**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 381 382| Name | Value | Description | 383| ---------| ------------| --------------| 384| INSERT | 0 | Data is added.| 385| DELETE | 1 | Data is deleted.| 386| UPDATE | 2 | Data is updated.| 387 388## SubscriptionType<sup>12+</sup> 389 390Enumerates the data subscription types. 391 392**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 393 394| Name | Value | Description | 395| ----------------------------|------| ---------------------------- | 396| SUBSCRIPTION_TYPE_EXACT_URI | 0 | Data change of the specified URI.| 397 398## ChangeInfo<sup>12+</sup> 399 400Represents the data change information, including the data change type, URI of the data changed, and changed data content. 401 402**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 403 404| Name | Type | Mandatory| Description | 405| ---------- | ------------------------------------------------------------ | ---- | -------------- | 406| type | [ChangeType](#changetype12) | Yes | Data change type.| 407| uri | string | Yes | URI of the data changed. | 408| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)>| Yes | Changed data. | 409 410## DataShareHelper 411 412Provides a **DataShareHelper** instance to access or manage data on the server. Before calling an API provided by **DataShareHelper**, you must create a **DataShareHelper** instance using [createDataShareHelper](#datasharecreatedatasharehelper). 413 414### on('dataChange') 415 416on(type: 'dataChange', uri: string, callback: AsyncCallback<void>): void 417 418Subscribes to the data change of the specified URI. After an observer is registered, the subscriber will receive a notification when the **notifyChange()** API is called. This API uses an asynchronous callback to return the result. 419 420**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 421 422**Parameters** 423 424| Name | Type | Mandatory| Description | 425| -------- | -------------------- | ---- | ------------------------ | 426| type | string | Yes | Event/callback type. The value is **dataChange**, which indicates the data change.| 427| uri | string | Yes | URI of the data to be observed.| 428| callback | AsyncCallback<void> | Yes | Callback used to return the data change. If the data is changed, **err** is **undefined**. Otherwise, this callback is not invoked or **err** is an error object.| 429 430**Error codes** 431 432For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 433 434| ID| Error Message | 435| -------- | -------------------- | 436| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 437| 15700013 | The DataShareHelper instance is already closed.| 438 439**Example** 440 441```ts 442let onCallback: () => void = (): void => { 443 console.info("**** Observer on callback ****"); 444} 445let uri = ("datashare:///com.samples.datasharetest.DataShare"); 446if (dataShareHelper !== undefined) { 447 (dataShareHelper as dataShare.DataShareHelper).on("dataChange", uri, onCallback); 448} 449``` 450 451### on('dataChange')<sup>12+</sup> 452 453on(event: 'dataChange', type:SubscriptionType, uri: string, callback: AsyncCallback<ChangeInfo>): void 454 455Subscribes to the data change of the specified URI. This API uses an asynchronous callback to return the result. After a change notification is registered, the subscriber will receive a notification when the **notifyChange()** API is called. The change notification contains the data change type, URI of the data changed, and the changed data. Silent access is not supported. 456 457**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 458 459**Parameters** 460 461| Name | Type | Mandatory| Description | 462| -------- | -------------------- | ---- | ------------------------ | 463| event | string | Yes | Event/callback type. The value is **dataChange**, which indicates the data change.| 464| type | [SubscriptionType](#subscriptiontype12)| Yes | Subscription type.| 465| uri | string | Yes | URI of the data to be observed.| 466| callback | AsyncCallback<[ChangeInfo](#changeinfo12)> | Yes | Callback used to return the data change when the change notification is triggered.| 467 468**Error codes** 469 470For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 471 472| ID| Error Message | 473| -------- | -------------------- | 474| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 475| 15700013 | The DataShareHelper instance is already closed.| 476 477**Example** 478 479<!--code_no_check--> 480```ts 481import { BusinessError } from '@kit.BasicServicesKit' 482 483let uri = ("datashare:///com.acts.datasharetest"); 484export function callback(error:BusinessError, ChangeInfo:dataShare.ChangeInfo) { 485 console.info(' **** Observer callback **** ChangeInfo:' + JSON.stringify(ChangeInfo)); 486} 487if (dataShareHelper !== undefined) { 488 (dataShareHelper as dataShare.DataShareHelper).on('dataChange', dataShare.SubscriptionType.SUBSCRIPTION_TYPE_EXACT_URI, uri, callback); 489} 490``` 491 492### off('dataChange') 493 494off(type: 'dataChange', uri: string, callback?: AsyncCallback<void>): void 495 496Unsubscribes from the data change of the specified URI. 497 498**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 499 500**Parameters** 501 502| Name | Type | Mandatory| Description | 503| -------- | -------------------- | ---- | ------------------------ | 504| type | string | Yes | Event/callback type. The value is **dataChange**, which indicates the data change.| 505| uri | string | Yes | URI of the data to be observed.| 506| callback | AsyncCallback<void> | No | Callback to unregister. If this parameter is **undefined**, **null**, or left empty, this API unregisters all callbacks for the specified URI.| 507 508**Error codes** 509 510For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 511 512| ID| Error Message | 513| -------- | -------------------- | 514| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 515| 15700013 | The DataShareHelper instance is already closed.| 516 517**Example** 518 519```ts 520let callback: () => void = (): void => { 521 console.info("**** Observer on callback ****"); 522} 523let uri = ("datashare:///com.samples.datasharetest.DataShare"); 524if (dataShareHelper != undefined) { 525 (dataShareHelper as dataShare.DataShareHelper).on("dataChange", uri, callback); 526 (dataShareHelper as dataShare.DataShareHelper).off("dataChange", uri, callback); 527} 528``` 529 530 531### off('dataChange')<sup>12+</sup> 532 533off(event: 'dataChange', type:SubscriptionType, uri: string, callback?: AsyncCallback<ChangeInfo>): void 534 535Unsubscribes from the data change of the specified URI. Silent access is not supported. 536 537**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 538 539**Parameters** 540 541| Name | Type | Mandatory| Description | 542| -------- | -------------------- | ---- | ------------------------ | 543| event | string | Yes | Event or callback type. The value is **dataChange**, which indicates the data change.| 544| type | [SubscriptionType](#subscriptiontype12)| Yes | Subscription type.| 545| uri | string | Yes | URI of the data to be observed.| 546| callback | AsyncCallback<[ChangeInfo](#changeinfo12)>| No | Callback to unregister. If this parameter is **undefined**, **null**, or left empty, this API unregisters all callbacks for the specified URI. If this parameter is specified, the callback must be the one registered in [on('datachange')](#ondatachange12).| 547 548**Error codes** 549 550For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 551 552| ID| Error Message | 553| -------- | -------------------- | 554| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 555| 15700013 | The DataShareHelper instance is already closed.| 556 557**Example** 558 559<!--code_no_check--> 560```ts 561import { BusinessError } from '@kit.BasicServicesKit' 562 563let uri = ("datashare:///com.acts.datasharetest"); 564export function callback(error:BusinessError, ChangeInfo:dataShare.ChangeInfo) { 565 console.info(' **** Observer callback **** ChangeInfo:' + JSON.stringify(ChangeInfo)); 566} 567if (dataShareHelper !== undefined) { 568 (dataShareHelper as dataShare.DataShareHelper).on("dataChange", dataShare.SubscriptionType.SUBSCRIPTION_TYPE_EXACT_URI, uri, callback); 569 (dataShareHelper as dataShare.DataShareHelper).off("dataChange", dataShare.SubscriptionType.SUBSCRIPTION_TYPE_EXACT_URI, uri, callback); 570} 571``` 572 573### addTemplate<sup>10+</sup> 574 575addTemplate(uri: string, subscriberId: string, template: Template): void 576 577Adds a data template with the specified subscriber. 578 579**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 580 581**Parameters** 582 583| Name | Type | Mandatory| Description | 584| -------- | ------------------------ | ---- | -------------------------| 585| uri | string | Yes | URI of the data to add. | 586| subscriberId | string | Yes | Unique ID of the template subscriber.| 587| template | [Template](#template10) | Yes | Data template to add. | 588 589**Error codes** 590 591For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 592 593| ID| Error Message | 594| -------- | -------------------- | 595| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 596| 15700011 | The URI is not exist.| 597| 15700013 | The DataShareHelper instance is already closed.| 598 599**Example** 600 601```ts 602let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 603let subscriberId = '11'; 604let key1: string = "p1"; 605let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true"; 606let key2: string = "p2"; 607let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false"; 608let template: dataShare.Template = { 609 predicates : { 610 key1 : value1, 611 key2 : value2, 612 }, 613 scheduler : "select remindTimer(time) from TBL00", 614 update : "update TBL00 set cityColumn = 'visited' where cityColumn = 'someCity'" 615} 616if (dataShareHelper != undefined) { 617 (dataShareHelper as dataShare.DataShareHelper).addTemplate(uri, subscriberId, template); 618} 619``` 620 621### delTemplate<sup>10+</sup> 622 623delTemplate(uri: string, subscriberId: string): void 624 625Deletes a data template based on the specified subscriber. 626 627**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 628 629**Parameters** 630 631| Name | Type | Mandatory| Description | 632| -------- | -------------| ---- | ------------------------- | 633| uri | string | Yes | URI of the data to delete. | 634| subscriberId | string | Yes | Unique ID of the subscriber. | 635 636**Error codes** 637 638For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 639 640| ID| Error Message | 641| -------- | -------------------- | 642| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 643| 15700011 | The URI is not exist.| 644| 15700013 | The DataShareHelper instance is already closed.| 645 646**Example** 647 648```ts 649let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 650let subscriberId = '11'; 651let key1: string = "p1"; 652let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true"; 653let key2: string = "p2"; 654let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false"; 655let template: dataShare.Template = { 656 predicates : { 657 key1 : value1, 658 key2 : value2, 659 }, 660 scheduler : "select remindTimer(time) from TBL00" 661} 662if (dataShareHelper != undefined) { 663 (dataShareHelper as dataShare.DataShareHelper).addTemplate(uri, subscriberId, template); 664 (dataShareHelper as dataShare.DataShareHelper).delTemplate(uri, subscriberId); 665} 666``` 667 668### on('rdbDataChange')<sup>10+</sup> 669 670on(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback: AsyncCallback<RdbDataChangeNode>): Array<OperationResult> 671 672Subscribes to the changes of the data corresponding to the specified URI and template. 673 674**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 675 676**Parameters** 677 678| Name | Type | Mandatory| Description | 679| -------- | ----------------------------------| ---- | ------------------------------------------------------------ | 680| type | string | Yes | Event type. The value is **rdbDataChange**, which indicates the change of the RDB data. If **type** is any other value, there is no response to this API. | 681| uris | Array<string> | Yes | URIs of the target data. | 682| templateId | [TemplateId](#templateid10) | Yes | ID of the template that triggers the callback. | 683| callback | AsyncCallback<[RdbDataChangeNode](#rdbdatachangenode10)> | Yes | Callback used to return the data change. If the operation is successful, **err** is **undefined** and **node** is the data changed. Otherwise, this callback is not invoked or **err** is an error object. | 684 685**Return value** 686 687| Type | Description | 688| ---------------- | ------------------------------------------------------------ | 689| Array<[OperationResult](#operationresult10)> | Returns the operation result.| 690 691**Error codes** 692 693For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 694 695| ID| Error Message | 696| -------- | -------------------- | 697| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 698| 15700013 | The DataShareHelper instance is already closed.| 699 700**Example** 701 702```ts 703import { BusinessError } from '@kit.BasicServicesKit' 704 705let onCallback: (err: BusinessError, node: dataShare.RdbDataChangeNode) => void = (err: BusinessError, node:dataShare.RdbDataChangeNode): void => { 706 console.info("onCallback " + JSON.stringify(node.uri)); 707 console.info("onCallback " + JSON.stringify(node.templateId)); 708 console.info("onCallback " + node.data.length); 709 for (let i = 0; i < node.data.length; i++) { 710 console.info("onCallback " + typeof node.data[i] + " " + node.data[i]); 711 } 712} 713 714let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 715let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"}; 716if (dataShareHelper != undefined) { 717 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).on("rdbDataChange", [uri], templateId, onCallback); 718} 719``` 720 721### off('rdbDataChange')<sup>10+</sup> 722 723off(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback?: AsyncCallback<RdbDataChangeNode>): Array<OperationResult> 724 725Unsubscribes from the changes of the data corresponding to the specified URI and template. 726 727**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 728 729**Parameters** 730 731| Name | Type | Mandatory| Description | 732| -------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | 733| type | string | Yes | Event type. The value is **rdbDataChange**, which indicates the change of the RDB data. | 734| uris | Array<string> | Yes | URIs of the target data. | 735| templateId | [TemplateId](#templateid10) | Yes | ID of the template that triggers the callback. | 736| callback | AsyncCallback<[RdbDataChangeNode](#rdbdatachangenode10)> | No | Callback to unregister. If this parameter is **undefined**, **null**, or left empty, this API unregisters all callbacks for the specified URI.| 737 738**Return value** 739 740| Type | Description | 741| ---------------- | ------------------------------------------------------------ | 742| Array<[OperationResult](#operationresult10)> | Returns the operation result.| 743 744**Error codes** 745 746For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 747 748| ID| Error Message | 749| -------- | -------------------- | 750| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 751| 15700013 | The DataShareHelper instance is already closed.| 752 753**Example** 754 755```ts 756let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 757let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"}; 758if (dataShareHelper != undefined) { 759 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).off("rdbDataChange", [uri], templateId); 760} 761``` 762 763### on('publishedDataChange')<sup>10+</sup> 764 765on(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, callback: AsyncCallback<PublishedDataChangeNode>): Array<OperationResult> 766 767Subscribes to the change of the published data. 768 769**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 770 771**Parameters** 772 773| Name | Type | Mandatory| Description | 774| -------- | ----------------------------------| ---- | ------------------------------------------------------------ | 775| type | string | Yes | Event type. The value is **publishedDataChange**, which indicates the change of the published data.| 776| uris | Array<string> | Yes | URIs of the target data. | 777| subscriberId | string | Yes | Subscriber ID of the callback. | 778| callback | AsyncCallback<[PublishedDataChangeNode](#publisheddatachangenode10)> | Yes | Callback used to return the data change. If the operation is successful, **err** is **undefined** and **node** is the data changed. Otherwise, this callback is not invoked or **err** is an error object. | 779 780**Return value** 781 782| Type | Description | 783| ---------------- | ------------------------------------------------------------ | 784| Array<[OperationResult](#operationresult10)> | Returns the operation result.| 785 786**Error codes** 787 788For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 789 790| ID| Error Message | 791| -------- | -------------------- | 792| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 793| 15700013 | The DataShareHelper instance is already closed.| 794 795**Example** 796 797```ts 798import { BusinessError } from '@kit.BasicServicesKit' 799 800let onPublishCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => { 801 console.info("onPublishCallback node bundleName " + JSON.stringify(node.bundleName)); 802 console.info("onPublishCallback node data size" + node.data.length); 803 for (let i = 0; i < node.data.length; i++) { 804 console.info("onPublishCallback node " + typeof node.data[i].data); 805 if (typeof node.data[i].data != 'string') { 806 let array: ArrayBuffer = node.data[i].data as ArrayBuffer; 807 let data: Uint8Array = new Uint8Array(array); 808 console.info("onPublishCallback " + i + " " + JSON.stringify(data)); 809 } 810 console.info("onPublishCallback data " + i + " " + JSON.stringify(node.data[i])); 811 } 812} 813let uris:Array<string> = ['city', 'datashareproxy://com.acts.ohos.data.datasharetest/appInfo', 'key2']; 814let subscriberId = '11'; 815if (dataShareHelper != undefined) { 816 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).on('publishedDataChange', uris, subscriberId, onPublishCallback); 817} 818``` 819 820### off('publishedDataChange')<sup>10+</sup> 821 822off(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, callback?: AsyncCallback<PublishedDataChangeNode>): Array<OperationResult> 823 824Unsubscribes from the change of the published data. 825 826**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 827 828**Parameters** 829 830| Name | Type | Mandatory| Description | 831| -------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | 832| type | string | Yes | Event type. The value is **publishedDataChange**, which indicates the change of the published data.| 833| uris | Array<string> | Yes | URIs of the target data. | 834| subscriberId | string | Yes | Subscriber ID of the callback. | 835| callback | AsyncCallback<[PublishedDataChangeNode](#publisheddatachangenode10)> | No | Callback to unregister. If this parameter is **undefined**, **null**, or left empty, this API unregisters all callbacks for the specified URI.| 836 837**Return value** 838 839| Type | Description | 840| ---------------- | ------------------------------------------------------------ | 841| Array<[OperationResult](#operationresult10)> | Returns the operation result.| 842 843**Error codes** 844 845For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 846 847| ID| Error Message | 848| -------- | -------------------- | 849| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 850| 15700013 | The DataShareHelper instance is already closed.| 851 852**Example** 853 854```ts 855import { BusinessError } from '@kit.BasicServicesKit' 856 857let offCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => { 858 console.info("**** Observer off callback ****"); 859} 860let uris:Array<string> = ["city", "datashareproxy://com.acts.ohos.data.datasharetest/appInfo", "key2"]; 861let subscriberId = '11'; 862if (dataShareHelper != undefined) { 863 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).off("publishedDataChange", uris, subscriberId, offCallback); 864} 865``` 866 867### publish<sup>10+</sup> 868 869publish(data: Array<PublishedItem>, bundleName: string, version: number, callback: AsyncCallback<Array<OperationResult>>): void 870 871Publishes data to the database. 872 873**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 874 875**Parameters** 876 877| Name | Type | Mandatory| Description | 878| --------- | -------------------------------------------------| ---- | ------------------- | 879| data | Array<[PublishedItem](#publisheditem10)> | Yes | Data to publish. | 880| bundleName | string | Yes | Application of the data to publish. This parameter is valid only for the private data published. Only the application can read the data. | 881| version | number | Yes | Version of the data to publish. A larger value indicates a later version. If the version of the data published is earlier than that of the data in the database, the data in the database will not be updated.| 882| callback | AsyncCallback<Array<[OperationResult](#operationresult10)>> | Yes | Callback used to return the result. If data is published, **err** is **undefined**, and **result** is the data publish result. Otherwise, this callback is not triggered or **err** is an error object. | 883 884**Error codes** 885 886For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 887 888| ID| Error Message | 889| -------- | -------------------------- | 890| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 891| 15700012 | The data area is not exist.| 892| 15700013 | The DataShareHelper instance is already closed.| 893 894**Example** 895 896```ts 897import { BusinessError } from '@kit.BasicServicesKit' 898 899let arrayBuffer = new ArrayBuffer(1); 900let version = 1; 901let dataArray : Array<dataShare.PublishedItem> = [{key:"key2", subscriberId:"11", data:arrayBuffer}]; 902let publishCallback: (err: BusinessError, result: Array<dataShare.OperationResult>) => void = (err: BusinessError, result: Array<dataShare.OperationResult>): void => { 903 console.info("publishCallback " + JSON.stringify(result)); 904} 905try { 906 console.info("dataArray length is:", dataArray.length); 907 if (dataShareHelper != undefined) { 908 (dataShareHelper as dataShare.DataShareHelper).publish(dataArray, "com.acts.ohos.data.datasharetest", version, publishCallback); 909 } 910} catch (e) { 911 console.error("publish error " + JSON.stringify(e)); 912} 913``` 914 915### publish<sup>10+</sup> 916 917publish(data: Array<PublishedItem>, bundleName: string, callback: AsyncCallback<Array<OperationResult>>): void 918 919Publishes data to the database. 920 921**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 922 923**Parameters** 924 925| Name | Type | Mandatory| Description | 926| -------- | ------------------------------------------------- | ---- | ---------------------------------- | 927| data | Array<[PublishedItem](#publisheditem10)> | Yes | Data to publish. | 928| bundleName | string | Yes | Application of the data to publish. This parameter is valid only for the private data published. Only the application can read the data. | 929| callback | AsyncCallback<Array<[OperationResult](#operationresult10)>> | Yes | Callback used to return the result. If data is published, **err** is **undefined**, and **result** is the data publish result. Otherwise, this callback is not triggered or **err** is an error object.| 930 931**Error codes** 932 933For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 934 935| ID| Error Message | 936| -------- | -------------------------- | 937| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 938| 15700012 | The data area is not exist.| 939| 15700013 | The DataShareHelper instance is already closed.| 940 941**Example** 942 943```ts 944import { BusinessError } from '@kit.BasicServicesKit' 945 946let publishCallback: (err: BusinessError, result: Array<dataShare.OperationResult>) => void = (err: BusinessError, result: Array<dataShare.OperationResult>): void => { 947 console.info("publishCallback " + JSON.stringify(result)); 948} 949let dataArray : Array<dataShare.PublishedItem> = [ 950 {key:"city", subscriberId:"11", data:"xian"}, 951 {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, 952 {key:"empty", subscriberId:"11", data:"nobody sub"}]; 953if (dataShareHelper != undefined) { 954 (dataShareHelper as dataShare.DataShareHelper).publish(dataArray, "com.acts.ohos.data.datasharetest", publishCallback); 955} 956``` 957 958### publish<sup>10+</sup> 959 960publish(data: Array<PublishedItem>, bundleName: string, version?: number): Promise<Array<OperationResult>> 961 962Publishes data to the database. 963 964**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 965 966**Parameters** 967 968| Name | Type | Mandatory| Description | 969| -------- | ----------------------------- | ---- | ------------------------------ | 970| data | Array<[PublishedItem](#publisheditem10)> | Yes | Data to publish.| 971| bundleName | string | Yes | Application of the data to publish. This parameter is valid only for the private data published. Only the application can read the data. | 972| version | number | No | Version of the data to publish. A larger value indicates a later version. If the version of the data published is earlier than that of the data in the database, the data in the database will not be updated.<br> If the data version is not checked, leave this parameter unspecified.| 973 974**Return value** 975 976| Type | Description | 977| ---------------- | ------------------------------------------------------------ | 978| Promise<Array<[OperationResult](#operationresult10)>> | Returns the operation result.| 979 980**Error codes** 981 982For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 983 984| ID| Error Message | 985| -------- | -------------------------- | 986| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 987| 15700012 | The data area is not exist.| 988| 15700013 | The DataShareHelper instance is already closed.| 989 990**Example** 991 992```ts 993let dataArray: Array<dataShare.PublishedItem> = [ 994 {key:"city", subscriberId:"11", data:"xian"}, 995 {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, 996 {key:"empty", subscriberId:"11", data:"nobody sub"}]; 997if (dataShareHelper != undefined) { 998 let result: Promise<Array<dataShare.OperationResult>> = (dataShareHelper as dataShare.DataShareHelper).publish(dataArray, "com.acts.ohos.data.datasharetest"); 999} 1000``` 1001 1002### getPublishedData<sup>10+</sup> 1003 1004getPublishedData(bundleName: string, callback: AsyncCallback<Array<PublishedItem>>): void 1005 1006Obtains the published data of an application. 1007 1008**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1009 1010**Parameters** 1011 1012| Name | Type | Mandatory| Description | 1013| -------- | -----------------| ---- | ----------------------------- | 1014| bundleName | string | Yes | Application to which the data belongs. | 1015| callback | AsyncCallback<Array<[PublishedItem](#publisheditem10)>> | Yes | Callback used to return the published data obtained.| 1016 1017**Error codes** 1018 1019For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1020 1021| ID| Error Message | 1022| -------- | -------------------------- | 1023| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1024| 15700012 | The data area is not exist.| 1025| 15700013 | The DataShareHelper instance is already closed.| 1026 1027**Example** 1028 1029```ts 1030import { BusinessError } from '@kit.BasicServicesKit' 1031 1032let publishCallback: (err: BusinessError, data: Array<dataShare.PublishedItem>) => void = (err: BusinessError, result: Array<dataShare.PublishedItem>): void => { 1033 console.info("**** Observer publish callback ****"); 1034} 1035if (dataShareHelper != undefined) { 1036 (dataShareHelper as dataShare.DataShareHelper).getPublishedData("com.acts.ohos.data.datasharetest", publishCallback); 1037} 1038``` 1039 1040### getPublishedData<sup>10+</sup> 1041 1042getPublishedData(bundleName: string): Promise<Array<PublishedItem>> 1043 1044Obtains the published data of an application. 1045 1046**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1047 1048**Parameters** 1049 1050| Name | Type | Mandatory| Description | 1051| -------- | --------------| ---- | -------------------------------------- | 1052| bundleName | string | Yes | Application to which the data belongs. | 1053 1054**Return value** 1055 1056| Type | Description | 1057| ------------------------------------------------------------ | ----------------------------------- | 1058| Promise<Array<[PublishedItem](#publisheditem10)>> | Promise used to return the published data obtained.| 1059 1060**Error codes** 1061 1062For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1063 1064| ID| Error Message | 1065| -------- | -------------------------- | 1066| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1067| 15700012 | The data area is not exist.| 1068| 15700013 | The DataShareHelper instance is already closed.| 1069 1070**Example** 1071 1072```ts 1073if (dataShareHelper != undefined) { 1074 let publishedData: Promise<Array<dataShare.PublishedItem>> = (dataShareHelper as dataShare.DataShareHelper).getPublishedData("com.acts.ohos.data.datasharetest"); 1075} 1076``` 1077 1078### insert 1079 1080insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void 1081 1082Inserts a single data record into the database. This API uses an asynchronous callback to return the result. 1083 1084**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1085 1086**Parameters** 1087 1088| Name | Type | Mandatory| Description | 1089| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | 1090| uri | string | Yes | URI of the data to insert. | 1091| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is left empty, a blank row will be inserted. | 1092| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the index of the inserted data record. Otherwise, **err** is an error object.<br>The data index is not returned if the APIs of the database in use, for example, the key-value database (KVDB), do not support the return of indexes.| 1093 1094**Error codes** 1095 1096For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1097 1098| ID| Error Message | 1099| -------- | -------------------- | 1100| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1101| 15700013 | The DataShareHelper instance is already closed.| 1102 1103**Example** 1104 1105```ts 1106import { ValuesBucket } from '@kit.ArkData' 1107import { BusinessError } from '@kit.BasicServicesKit' 1108 1109let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1110let key1: string = "name"; 1111let value1: string = "rose"; 1112let key2: string = "age"; 1113let value2: number = 22; 1114let key3: string = "salary"; 1115let value3: number = 200.5; 1116const valueBucket: ValuesBucket = { 1117 key1: value1, 1118 key2: value2, 1119 key3: value3, 1120} 1121try { 1122 if (dataShareHelper != undefined) { 1123 (dataShareHelper as dataShare.DataShareHelper).insert(uri, valueBucket, (err: BusinessError, data: number) => { 1124 if (err !== undefined) { 1125 console.error(`insert error: code: ${err.code}, message: ${err.message} `); 1126 return; 1127 } 1128 console.info("insert succeed, data : " + data); 1129 }); 1130 } 1131} catch (err) { 1132 let code = (err as BusinessError).code; 1133 let message = (err as BusinessError).message; 1134 console.error(`insert error: code: ${code}, message: ${message} `); 1135}; 1136``` 1137 1138### insert 1139 1140insert(uri: string, value: ValuesBucket): Promise<number> 1141 1142Inserts a single data record into the database. This API uses a promise to return the result. 1143 1144**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1145 1146**Parameters** 1147 1148| Name | Type | Mandatory| Description | 1149| ----- | --------------------------------------------------------- | ---- | -------------------------------------------------- | 1150| uri | string | Yes | URI of the data to insert. | 1151| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is left empty, a blank row will be inserted.| 1152 1153**Return value** 1154 1155| Type | Description | 1156| ---------------- | ------------------------------------------------------------ | 1157| Promise<number> | Promise used to return the index of the inserted data record.<br>The data index is not returned if the APIs of the database in use (for example, KVDB) do not support the return of indexes.| 1158 1159**Error codes** 1160 1161For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1162 1163| ID| Error Message | 1164| -------- | -------------------- | 1165| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1166| 15700013 | The DataShareHelper instance is already closed.| 1167 1168**Example** 1169 1170```ts 1171import { BusinessError } from '@kit.BasicServicesKit' 1172import { ValuesBucket } from '@kit.ArkData' 1173 1174let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1175let key1: string = "name"; 1176let value1: string = "rose1"; 1177let key2: string = "age"; 1178let value2: number = 21; 1179let key3: string = "salary"; 1180let value3: number = 20.5; 1181const valueBucket: ValuesBucket = { 1182 key1: value1, 1183 key2: value2, 1184 key3: value3, 1185} 1186try { 1187 if (dataShareHelper != undefined) { 1188 (dataShareHelper as dataShare.DataShareHelper).insert(uri, valueBucket).then((data: number) => { 1189 console.info("insert succeed, data : " + data); 1190 }).catch((err: BusinessError) => { 1191 console.error(`insert error: code: ${err.code}, message: ${err.message} `); 1192 }); 1193 } 1194} catch (err) { 1195 let code = (err as BusinessError).code; 1196 let message = (err as BusinessError).message; 1197 console.error(`insert error: code: ${code}, message: ${message} `); 1198}; 1199``` 1200 1201### delete 1202 1203delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>): void 1204 1205Deletes one or more data records from the database. This API uses an asynchronous callback to return the result. 1206 1207**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1208 1209**Parameters** 1210 1211| Name | Type | Mandatory| Description | 1212| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1213| uri | string | Yes | URI of the data to delete. | 1214| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions for deleting the data.<br>The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**. If this parameter is left empty, the entire table will be deleted by default.| 1215| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of deleted data records. Otherwise, **err** is an error object.<br>The number of deleted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| 1216 1217**Error codes** 1218 1219For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1220 1221| ID| Error Message | 1222| -------- | -------------------- | 1223| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1224| 15700013 | The DataShareHelper instance is already closed.| 1225 1226**Example** 1227 1228```ts 1229import { dataSharePredicates } from '@kit.ArkData' 1230import { BusinessError } from '@kit.BasicServicesKit' 1231 1232let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1233let da = new dataSharePredicates.DataSharePredicates(); 1234da.equalTo("name", "ZhangSan"); 1235try { 1236 if (dataShareHelper != undefined) { 1237 (dataShareHelper as dataShare.DataShareHelper).delete(uri, da, (err: BusinessError, data: number) => { 1238 if (err !== undefined) { 1239 console.error(`delete error: code: ${err.code}, message: ${err.message} `); 1240 return; 1241 } 1242 console.info("delete succeed, data : " + data); 1243 }); 1244 } 1245} catch (err) { 1246 let code = (err as BusinessError).code; 1247 let message = (err as BusinessError).message; 1248 console.error(`delete error: code: ${code}, message: ${message} `); 1249}; 1250``` 1251 1252### delete 1253 1254delete(uri: string, predicates: dataSharePredicates.DataSharePredicates): Promise<number> 1255 1256Deletes one or more data records from the database. This API uses a promise to return the result. 1257 1258**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1259 1260**Parameters** 1261 1262| Name | Type | Mandatory| Description | 1263| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1264| uri | string | Yes | URI of the data to delete. | 1265| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions for deleting the data.<br>The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**. If this parameter is left empty, the entire table will be deleted by default.| 1266 1267**Return value** 1268 1269| Type | Description | 1270| ---------------- | ------------------------------------------------------------ | 1271| Promise<number> | Promise used to return the number of deleted data records.<br>The number of deleted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| 1272 1273**Error codes** 1274 1275For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1276 1277| ID| Error Message | 1278| -------- | -------------------- | 1279| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1280| 15700013 | The DataShareHelper instance is already closed.| 1281 1282**Example** 1283 1284```ts 1285import { dataSharePredicates } from '@kit.ArkData' 1286import { BusinessError } from '@kit.BasicServicesKit' 1287 1288let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1289let da = new dataSharePredicates.DataSharePredicates(); 1290da.equalTo("name", "ZhangSan"); 1291try { 1292 if (dataShareHelper != undefined) { 1293 (dataShareHelper as dataShare.DataShareHelper).delete(uri, da).then((data: number) => { 1294 console.info("delete succeed, data : " + data); 1295 }).catch((err: BusinessError) => { 1296 console.error(`delete error: code: ${err.code}, message: ${err.message} `); 1297 }); 1298 } 1299} catch (err) { 1300 let code = (err as BusinessError).code; 1301 let message = (err as BusinessError).message; 1302 console.error(`delete error: code: ${code}, message: ${message} `); 1303}; 1304``` 1305 1306### query 1307 1308query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void 1309 1310Queries data in the database. This API uses an asynchronous callback to return the result. 1311 1312**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1313 1314**Parameters** 1315 1316| Name | Type | Mandatory| Description | 1317| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1318| uri | string | Yes | URI of the data to query. | 1319| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions for querying the data.<br>The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**. If this parameter is left empty, the entire table will be queried by default.| 1320| columns | Array<string> | Yes | Column to query. If this parameter is left empty, all columns will be queried. | 1321| callback | AsyncCallback<[DataShareResultSet](js-apis-data-DataShareResultSet-sys.md#datashareresultset)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the result set obtained. Otherwise, **err** is an error object.| 1322 1323**Error codes** 1324 1325For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1326 1327| ID| Error Message | 1328| -------- | -------------------- | 1329| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1330| 15700013 | The DataShareHelper instance is already closed.| 1331 1332**Example** 1333 1334```ts 1335import { dataSharePredicates, DataShareResultSet } from '@kit.ArkData' 1336import { BusinessError } from '@kit.BasicServicesKit' 1337 1338let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1339let columns = ["*"]; 1340let da = new dataSharePredicates.DataSharePredicates(); 1341da.equalTo("name", "ZhangSan"); 1342try { 1343 if (dataShareHelper != undefined) { 1344 (dataShareHelper as dataShare.DataShareHelper).query(uri, da, columns, (err: BusinessError, data: DataShareResultSet) => { 1345 if (err !== undefined) { 1346 console.error(`query error: code: ${err.code}, message: ${err.message} `); 1347 return; 1348 } 1349 console.info("query succeed, rowCount : " + data.rowCount); 1350 }); 1351 } 1352} catch (err) { 1353 let code = (err as BusinessError).code; 1354 let message = (err as BusinessError).message; 1355 console.error(`query error: code: ${code}, message: ${message} `); 1356}; 1357``` 1358 1359### query 1360 1361query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>): Promise<DataShareResultSet> 1362 1363Queries data in the database. This API uses a promise to return the result. 1364 1365**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1366 1367**Parameters** 1368 1369| Name | Type | Mandatory| Description | 1370| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1371| uri | string | Yes | URI of the data to query. | 1372| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions for querying the data.<br>The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**. If this parameter is left empty, the entire table will be queried by default.| 1373| columns | Array<string> | Yes | Column to query. If this parameter is left empty, all columns will be queried. | 1374 1375**Return value** 1376 1377| Type | Description | 1378| ------------------------------------------------------------ | --------------------------------- | 1379| Promise<[DataShareResultSet](js-apis-data-DataShareResultSet-sys.md#datashareresultset)> | Promise used to return the result set obtained.| 1380 1381**Error codes** 1382 1383For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1384 1385| ID| Error Message | 1386| -------- | -------------------- | 1387| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1388| 15700013 | The DataShareHelper instance is already closed.| 1389 1390**Example** 1391 1392```ts 1393import { dataSharePredicates, DataShareResultSet } from '@kit.ArkData' 1394import { BusinessError } from '@kit.BasicServicesKit' 1395 1396let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1397let columns = ["*"]; 1398let da = new dataSharePredicates.DataSharePredicates(); 1399da.equalTo("name", "ZhangSan"); 1400try { 1401 if (dataShareHelper != undefined) { 1402 (dataShareHelper as dataShare.DataShareHelper).query(uri, da, columns).then((data: DataShareResultSet) => { 1403 console.info("query succeed, rowCount : " + data.rowCount); 1404 }).catch((err: BusinessError) => { 1405 console.error(`query error: code: ${err.code}, message: ${err.message} `); 1406 }); 1407 } 1408} catch (err) { 1409 let code = (err as BusinessError).code; 1410 let message = (err as BusinessError).message; 1411 console.error(`query error: code: ${code}, message: ${message} `); 1412}; 1413``` 1414 1415### update 1416 1417update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void 1418 1419Updates data in the database. This API uses an asynchronous callback to return the result. 1420 1421**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1422 1423**Parameters** 1424 1425| Name | Type | Mandatory| Description | 1426| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1427| uri | string | Yes | URI of the data to update. | 1428| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions for updating the data.<br>The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates. If this parameter is left empty, the entire table will be updated by default.| 1429| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data, which can be null. | 1430| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of updated data records. Otherwise, **err** is an error object.<br>The number of updated data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| 1431 1432**Error codes** 1433 1434For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1435 1436| ID| Error Message | 1437| -------- | -------------------- | 1438| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1439| 15700013 | The DataShareHelper instance is already closed.| 1440 1441**Example** 1442 1443```ts 1444import { dataSharePredicates, ValuesBucket } from '@kit.ArkData' 1445import { BusinessError } from '@kit.BasicServicesKit' 1446 1447let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1448let da = new dataSharePredicates.DataSharePredicates(); 1449da.equalTo("name", "ZhangSan"); 1450let key1: string = "name"; 1451let value1: string = "roe1" 1452let key2: string = "age"; 1453let value2: number = 21 1454let key3: string = "salary"; 1455let value3: number = 20.5; 1456const va: ValuesBucket = { 1457 key1: value1, 1458 key2: value2, 1459 key3: value3, 1460} 1461try { 1462 if (dataShareHelper != undefined) { 1463 (dataShareHelper as dataShare.DataShareHelper).update(uri, da, va, (err: BusinessError, data: number) => { 1464 if (err !== undefined) { 1465 console.error(`update error: code: ${err.code}, message: ${err.message} `); 1466 return; 1467 } 1468 console.info("update succeed, data : " + data); 1469 }); 1470 } 1471} catch (err) { 1472 let code = (err as BusinessError).code; 1473 let message = (err as BusinessError).message; 1474 console.error(`update error: code: ${code}, message: ${message} `); 1475}; 1476``` 1477 1478### update 1479 1480update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket): Promise<number> 1481 1482Updates data in the database. This API uses a promise to return the result. 1483 1484**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1485 1486**Parameters** 1487 1488| Name | Type | Mandatory| Description | 1489| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1490| uri | string | Yes | URI of the data to update. | 1491| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions for updating the data.<br>The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates. If this parameter is left empty, the entire table will be updated by default.| 1492| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data, which can be null. | 1493 1494**Return value** 1495 1496| Type | Description | 1497| ---------------- | ------------------------------------------------------------ | 1498| Promise<number> | Promise used to return the number of data records updated.<br>The number of updated data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| 1499 1500**Error codes** 1501 1502For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1503 1504| ID| Error Message | 1505| -------- | -------------------- | 1506| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1507| 15700013 | The DataShareHelper instance is already closed.| 1508 1509**Example** 1510 1511```ts 1512import { dataSharePredicates, ValuesBucket } from '@kit.ArkData' 1513import { BusinessError } from '@kit.BasicServicesKit' 1514 1515let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1516let da = new dataSharePredicates.DataSharePredicates(); 1517da.equalTo("name", "ZhangSan"); 1518let key1: string = "name"; 1519let value1: string = "roe1" 1520let key2: string = "age"; 1521let value2: number = 21 1522let key3: string = "salary"; 1523let value3: number = 20.5; 1524const va: ValuesBucket = { 1525 key1: value1, 1526 key2: value2, 1527 key3: value3, 1528} 1529try { 1530 if (dataShareHelper != undefined) { 1531 (dataShareHelper as dataShare.DataShareHelper).update(uri, da, va).then((data: number) => { 1532 console.info("update succeed, data : " + data); 1533 }).catch((err: BusinessError) => { 1534 console.error(`update error: code: ${err.code}, message: ${err.message} `); 1535 }); 1536 } 1537} catch (err) { 1538 let code = (err as BusinessError).code; 1539 let message = (err as BusinessError).message; 1540 console.error(`update error: code: ${code}, message: ${message} `); 1541}; 1542``` 1543 1544### batchUpdate<sup>12+</sup> 1545 1546batchUpdate(operations: Record<string, Array<UpdateOperation>>): Promise<Record<string, Array<number>>> 1547 1548Updates data in batches. A maximum of 900 KB data can be updated at a time. If the data volume exceeds 900 KB, the update will fail. The transaction of this API depends on the data provider. This API uses a promise to return the result. Silent access is not supported currently. 1549 1550**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1551 1552**Parameters** 1553 1554| Name | Type | Mandatory| Description | 1555| ---------- | ------------------------------------------------------------ | ---- | -------------------------------------- | 1556| operations | Record<string, Array<[UpdateOperation](#updateoperation12)>> | Yes | Collection of the path of the data to update, update conditions, and new data.| 1557 1558**Return value** 1559 1560| Type | Description | 1561| ----------------------------------------------------- | ------------------------------------------------------------ | 1562| Promise<Record<string, Array<number>>> | Promise used to return an array of updated data records. The value **-1** means the update operation fails.<br>The number of updated data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| 1563 1564**Error codes** 1565 1566For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1567 1568| ID| Error Message | 1569| -------- | ------------------------------------ | 1570| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1571| 15700000 | Inner error. | 1572| 15700013 | The DataShareHelper instance is already closed. | 1573 1574**Example** 1575 1576```ts 1577import { dataSharePredicates, ValuesBucket } from '@kit.ArkData' 1578import { BusinessError } from '@kit.BasicServicesKit' 1579 1580let record: Record<string, Array<dataShare.UpdateOperation>> = {}; 1581let operations1: Array<dataShare.UpdateOperation> = []; 1582let operations2: Array<dataShare.UpdateOperation> = []; 1583 1584let pre1: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); 1585pre1.equalTo("name", "ZhangSan"); 1586let vb1: ValuesBucket = { 1587 "name": "ZhangSan1", 1588} 1589let operation1: dataShare.UpdateOperation = { 1590 values: vb1, 1591 predicates: pre1 1592} 1593operations1.push(operation1); 1594 1595let pre2: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates(); 1596pre2.equalTo("name", "ZhangSan2"); 1597let vb2: ValuesBucket = { 1598 "name": "ZhangSan3", 1599} 1600let operation2: dataShare.UpdateOperation = { 1601 values: vb2, 1602 predicates: pre2 1603} 1604operations2.push(operation2); 1605record["uri1"] = operations1; 1606record["uri2"] = operations2; 1607 1608try { 1609 if (dataShareHelper != undefined) { 1610 (dataShareHelper as dataShare.DataShareHelper).batchUpdate(record).then((data: Record<string, Array<number>>) => { 1611 // Traverse data to obtain the update result of each data record. value indicates the number of data records that are successfully updated. If value is less than 0, the update fails. 1612 let a = Object.entries(data); 1613 for (let i = 0; i < a.length; i++) { 1614 let key = a[i][0]; 1615 let values = a[i][1] 1616 console.info(`Update uri:${key}`); 1617 for (const value of values) { 1618 console.info(`Update result:${value}`); 1619 } 1620 } 1621 }).catch((err: BusinessError) => { 1622 console.error(`Batch update error: code: ${err.code}, message: ${err.message} `); 1623 }); 1624 } 1625} catch (err) { 1626 let code = (err as BusinessError).code; 1627 let message = (err as BusinessError).message; 1628 console.error(`Batch update error: code: ${code}, message: ${message} `); 1629}; 1630``` 1631 1632### batchInsert 1633 1634batchInsert(uri: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>): void 1635 1636Batch inserts data into the database. This API uses an asynchronous callback to return the result. Silent access is not supported currently. 1637 1638**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1639 1640**Parameters** 1641 1642| Name | Type | Mandatory| Description | 1643| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1644| uri | string | Yes | URI of the data to insert. | 1645| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | 1646| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of data records inserted. Otherwise, **err** is an error object.<br>The number of inserted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| 1647 1648**Error codes** 1649 1650For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1651 1652| ID| Error Message | 1653| -------- | -------------------- | 1654| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1655| 15700013 | The DataShareHelper instance is already closed.| 1656 1657**Example** 1658 1659```ts 1660import { ValuesBucket } from '@kit.ArkData' 1661import { BusinessError } from '@kit.BasicServicesKit' 1662 1663let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1664let key1: string = "name"; 1665let value11: string = "roe11" 1666let key2: string = "age"; 1667let value21: number = 21; 1668let key3: string = "salary"; 1669let value31: number = 20.5; 1670let valuesBucket1: ValuesBucket = { 1671 key1: value11, 1672 key2: value21, 1673 key3: value31, 1674} 1675let vbs = new Array(valuesBucket1); 1676try { 1677 if (dataShareHelper != undefined) { 1678 (dataShareHelper as dataShare.DataShareHelper).batchInsert(uri, vbs, (err, data) => { 1679 if (err !== undefined) { 1680 console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); 1681 return; 1682 } 1683 console.info("batchInsert succeed, data : " + data); 1684 }); 1685 } 1686} catch (err) { 1687 let code = (err as BusinessError).code; 1688 let message = (err as BusinessError).message; 1689 console.error(`batchInsert error: code: ${code}, message: ${message} `); 1690}; 1691``` 1692 1693### batchInsert 1694 1695batchInsert(uri: string, values: Array<ValuesBucket>): Promise<number> 1696 1697Batch inserts data into the database. This API uses a promise to return the result. Silent access is not supported currently. 1698 1699**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1700 1701**Parameters** 1702 1703| Name | Type | Mandatory| Description | 1704| ------ | ------------------------------------------------------------ | ---- | ------------------------ | 1705| uri | string | Yes | URI of the data to insert.| 1706| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | 1707 1708**Return value** 1709 1710| Type | Description | 1711| ---------------- | ------------------------------------------------------------ | 1712| Promise<number> | Promise used to return the number of data records inserted.<br>The number of inserted data records is not returned if the APIs of the database (for example, KVDB) in use do not the return of the number of data records.| 1713 1714**Error codes** 1715 1716For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1717 1718| ID| Error Message | 1719| -------- | -------------------- | 1720| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1721| 15700013 | The DataShareHelper instance is already closed.| 1722 1723**Example** 1724 1725```ts 1726import { ValuesBucket } from '@kit.ArkData' 1727import { BusinessError } from '@kit.BasicServicesKit' 1728 1729let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1730let key1: string = "name"; 1731let value11: string = "roe11" 1732let key2: string = "age"; 1733let value21: number = 21; 1734let key3: string = "salary"; 1735let value31: number = 20.5; 1736let valuesBucket1: ValuesBucket = { 1737 key1: value11, 1738 key2: value21, 1739 key3: value31, 1740} 1741let vbs = new Array(valuesBucket1); 1742try { 1743 if (dataShareHelper != undefined) { 1744 (dataShareHelper as dataShare.DataShareHelper).batchInsert(uri, vbs).then((data: number) => { 1745 console.info("batchInsert succeed, data : " + data); 1746 }).catch((err: BusinessError) => { 1747 console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); 1748 }); 1749 } 1750} catch (err) { 1751 let code = (err as BusinessError).code; 1752 let message = (err as BusinessError).message 1753 console.error(`batchInsert error: code: ${code}, message: ${message} `); 1754}; 1755``` 1756 1757### close<sup>12+</sup> 1758 1759close(): Promise <void> 1760 1761Closes the **DataShareHelper** instance. After this API is called, the instance becomes invalid. This API uses a promise to return the result. 1762 1763**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1764 1765**Return value** 1766 1767| Type | Description | 1768| ------------------- | -------------------------------------- | 1769| Promise<void> | returns no value.| 1770 1771**Error codes** 1772 1773For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md). 1774 1775| ID| Error Message | 1776| -------- | ------------ | 1777| 15700000 | Inner error. | 1778 1779**Example** 1780 1781```ts 1782if (dataShareHelper != undefined) { 1783 (dataShareHelper as dataShare.DataShareHelper).close(); 1784} 1785``` 1786 1787### normalizeUri 1788 1789normalizeUri(uri: string, callback: AsyncCallback<string>): void 1790 1791Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses an asynchronous callback to return the result. Silent access is not supported currently. 1792 1793**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1794 1795**Parameters** 1796 1797| Name | Type | Mandatory| Description | 1798| -------- | ---------------------- | ---- | -------------------------------------------------------- | 1799| uri | string | Yes | [URI](../apis-arkts/js-apis-uri.md#uri) to normalize. | 1800| callback | AsyncCallback<string> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the normalized URI (if **null** is returned, URI normalization is not supported). Otherwise, **err** is an error object.| 1801 1802**Error codes** 1803 1804For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1805 1806| ID| Error Message | 1807| -------- | -------------------- | 1808| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1809| 15700013 | The DataShareHelper instance is already closed.| 1810 1811**Example** 1812 1813```ts 1814import { BusinessError } from '@kit.BasicServicesKit' 1815 1816let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1817if (dataShareHelper != undefined) { 1818 (dataShareHelper as dataShare.DataShareHelper).normalizeUri(uri, (err: BusinessError, data: string) => { 1819 if (err !== undefined) { 1820 console.info("normalizeUri failed, error message : " + err); 1821 } else { 1822 console.info("normalizeUri = " + data); 1823 } 1824 }); 1825} 1826``` 1827 1828### normalizeUri 1829 1830normalizeUri(uri: string): Promise<string> 1831 1832Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the local device, but the normalized URI can be used across devices. This API uses a promise to return the result. Silent access is not supported currently. 1833 1834**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1835 1836**Parameters** 1837 1838| Name| Type | Mandatory| Description | 1839| ---- | ------ | ---- | ----------------------------------------- | 1840| uri | string | Yes | [URI](../apis-arkts/js-apis-uri.md#uri) to normalize.| 1841 1842**Return value** 1843 1844| Type | Description | 1845| ---------------- | ---------------------------------------------- | 1846| Promise<string> | Promise used to return the result. If URI normalization is supported, the normalized URI is returned. Otherwise, **null** is returned.| 1847 1848**Error codes** 1849 1850For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1851 1852| ID| Error Message | 1853| -------- | -------------------- | 1854| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1855| 15700013 | The DataShareHelper instance is already closed.| 1856 1857**Example** 1858 1859```ts 1860import { BusinessError } from '@kit.BasicServicesKit' 1861 1862let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1863if (dataShareHelper != undefined) { 1864 (dataShareHelper as dataShare.DataShareHelper).normalizeUri(uri).then((data: string) => { 1865 console.info("normalizeUri = " + data); 1866 }).catch((err: BusinessError) => { 1867 console.info("normalizeUri failed, error message : " + err); 1868 }); 1869} 1870``` 1871 1872### denormalizeUri 1873 1874denormalizeUri(uri: string, callback: AsyncCallback<string>): void 1875 1876Denormalizes a URI. This API uses an asynchronous callback to return the result. Silent access is not supported currently. 1877 1878**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1879 1880**Parameters** 1881 1882| Name | Type | Mandatory| Description | 1883| -------- | ---------------------- | ---- | --------------------------------------------------- | 1884| uri | string | Yes | [URI](../apis-arkts/js-apis-uri.md#uri) to denormalize.| 1885| callback | AsyncCallback<string> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the URI obtained. If the original URI is returned, denormalization is not required. If **null** is returned, denormalization is not supported. If the operation fails, **err** is an error object.| 1886 1887**Error codes** 1888 1889For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1890 1891| ID| Error Message | 1892| -------- | -------------------- | 1893| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1894| 15700013 | The DataShareHelper instance is already closed.| 1895 1896**Example** 1897 1898```ts 1899import { BusinessError } from '@kit.BasicServicesKit' 1900 1901let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1902if (dataShareHelper != undefined) { 1903 (dataShareHelper as dataShare.DataShareHelper).denormalizeUri(uri, (err: BusinessError, data: string) => { 1904 if (err !== undefined) { 1905 console.error("denormalizeUri failed, error message : " + err); 1906 } else { 1907 console.info("denormalizeUri = " + data); 1908 } 1909 }); 1910} 1911``` 1912 1913### denormalizeUri 1914 1915denormalizeUri(uri: string): Promise<string> 1916 1917Denormalizes a URI. This API uses a promise to return the result. Silent access is not supported currently. 1918 1919**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1920 1921**Parameters** 1922 1923| Name| Type | Mandatory| Description | 1924| ---- | ------ | ---- | ------------------------------------------- | 1925| uri | string | Yes | [URI](../apis-arkts/js-apis-uri.md#uri) to denormalize.| 1926 1927**Return value** 1928 1929| Type | Description | 1930| ---------------- | ----------------------------------------- | 1931| Promise<string> | Promise used to return the result. If the denormalization is successful, the URI obtained is returned. If no operation is required, the original URI is returned. If denormalization is not supported, **null** is returned.| 1932 1933**Error codes** 1934 1935For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1936 1937| ID| Error Message | 1938| -------- | -------------------- | 1939| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 1940| 15700013 | The DataShareHelper instance is already closed.| 1941 1942**Example** 1943 1944```ts 1945import { BusinessError } from '@kit.BasicServicesKit' 1946 1947let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1948if (dataShareHelper != undefined) { 1949 (dataShareHelper as dataShare.DataShareHelper).denormalizeUri(uri).then((data: string) => { 1950 console.info("denormalizeUri = " + data); 1951 }).catch((err: BusinessError) => { 1952 console.error("denormalizeUri failed, error message : " + err); 1953 }); 1954} 1955``` 1956 1957### notifyChange 1958 1959notifyChange(uri: string, callback: AsyncCallback<void>): void 1960 1961Notifies the registered observer of data changes. This API uses an asynchronous callback to return the result. Silent access is not supported currently. 1962 1963**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1964 1965**Parameters** 1966 1967| Name | Type | Mandatory| Description | 1968| -------- | -------------------- | ---- | ------------------------ | 1969| uri | string | Yes | URI of the data.| 1970| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the observer is notified of the data changes, **err** is **undefined**. Otherwise, **err** is an error object.| 1971 1972**Error codes** 1973 1974For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 1975 1976| ID| Error Message | 1977| -------- | -------------------- | 1978| 401 | Parameter error.Mandatory parameters are left unspecified.| 1979| 15700013 | The DataShareHelper instance is already closed.| 1980 1981**Example** 1982 1983```ts 1984let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1985if (dataShareHelper != undefined) { 1986 (dataShareHelper as dataShare.DataShareHelper).notifyChange(uri, () => { 1987 console.info("***** notifyChange *****"); 1988 }); 1989} 1990``` 1991 1992### notifyChange 1993 1994notifyChange(uri: string): Promise<void> 1995 1996Notifies the registered observer of data changes. This API uses a promise to return the result. Silent access is not supported currently. 1997 1998**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1999 2000**Parameters** 2001 2002| Name| Type | Mandatory| Description | 2003| ---- | ------ | ---- | -------------------- | 2004| uri | string | Yes | URI of the data.| 2005 2006**Return value** 2007 2008| Type | Description | 2009| -------------- | --------------------- | 2010| Promise<void> | Promise that returns no value.| 2011 2012**Error codes** 2013 2014For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 2015 2016| ID| Error Message | 2017| -------- | -------------------- | 2018| 401 | Parameter error.Mandatory parameters are left unspecified.| 2019| 15700013 | The DataShareHelper instance is already closed.| 2020 2021**Example** 2022 2023```ts 2024let uri = ("datashare:///com.samples.datasharetest.DataShare"); 2025if (dataShareHelper != undefined) { 2026 (dataShareHelper as dataShare.DataShareHelper).notifyChange(uri); 2027} 2028``` 2029 2030### notifyChange<sup>12+</sup> 2031 2032notifyChange(data: ChangeInfo): Promise<void> 2033 2034Notifies the observer of the data change of the specified URI. This API uses a promise to return the result. Silent access is not supported. 2035 2036**System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 2037 2038**Parameters** 2039 2040| Name| Type | Mandatory| Description | 2041| ---- | ------ | ---- | -------------------- | 2042| data | [ChangeInfo](#changeinfo12) | Yes | Information about the data change type, URI of the data changed, and changed data.| 2043 2044**Return value** 2045 2046| Type | Description | 2047| -------------- | --------------------- | 2048| Promise<void> | returns no value.| 2049 2050**Error codes** 2051 2052For details about the error codes, see [DataShare Error Codes](errorcode-datashare.md) and [Universal Error Codes](../errorcode-universal.md). 2053 2054| ID| Error Message | 2055| -------- | -------------------- | 2056| 401 | Parameter error.Possible causes:1.Mandatory parameters are left unspecified; 2.Incorrect parameters types.| 2057| 15700013 | The DataShareHelper instance is already closed.| 2058 2059**Example** 2060 2061```ts 2062import { ValuesBucket } from '@kit.ArkData' 2063 2064let dsUri = ("datashare:///com.acts.datasharetest"); 2065let bucket1: ValuesBucket = {"name": "LiSi"}; 2066let bucket2: ValuesBucket = {"name": "WangWu"}; 2067let bucket3: ValuesBucket = {"name": "ZhaoLiu"}; 2068let people: Array<ValuesBucket> = new Array(bucket1, bucket2, bucket3); 2069let changeData:dataShare.ChangeInfo= { type:dataShare.ChangeType.INSERT, uri:dsUri, values:people}; 2070if (dataShareHelper != undefined) { 2071 (dataShareHelper as dataShare.DataShareHelper).notifyChange(changeData); 2072} 2073``` 2074