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