1 # @ohos.data.dataShare (Data Sharing) 2 3 The **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 17 import dataShare from '@ohos.data.dataShare' 18 ``` 19 20 ## dataShare.createDataShareHelper 21 22 createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void 23 24 Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result. 25 26 Observe the following when using this API: 27 - If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. 28 - If **exported** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. 29 - 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). 30 31 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 32 33 **Parameters** 34 35 | Name | Type | Mandatory| Description | 36 | -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | 37 | context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of the application. | 38 | uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect. | 39 | callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback invoked 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.| 40 41 **Error codes** 42 43 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 44 45 | ID| Error Message | 46 | -------- | ---------------------------------------------------- | 47 | 15700010 | The DataShareHelper is not initialized successfully. | 48 49 **Example** 50 51 ```ts 52 import { BusinessError } from '@ohos.base' 53 import UIAbility from '@ohos.app.ability.UIAbility'; 54 55 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 56 let dataShareHelper: dataShare.DataShareHelper | undefined = undefined; 57 let context = getContext(UIAbility); 58 try { 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> 75 createDataShareHelper(context: Context, uri: string, options: DataShareHelperOptions, callback: AsyncCallback<DataShareHelper>): void 76 77 Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result. 78 79 Observe the following when using this API: 80 - If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. 81 - If **exported** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. 82 - 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). 83 84 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 85 86 87 | Name | Type | Mandatory| Description | 88 | -------- | -------------------------------------------------------- | ---- | ------------------------------------------------------------ | 89 | context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of the application. | 90 | uri | string | Yes | URI of the server application to connect. | 91 | options | [DataShareHelperOptions](#datasharehelperoptions10)| Yes | Configuration specifying whether [DataShareHelper](#datasharehelper) is in proxy mode.| 92 | callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback invoked 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.| 93 94 **Error codes** 95 96 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 97 98 | ID| Error Message | 99 | -------- | ---------------------------------------------------- | 100 | 15700010 | The DataShareHelper is not initialized successfully. | 101 102 **Example** 103 104 ```ts 105 import { BusinessError } from '@ohos.base' 106 import UIAbility from '@ohos.app.ability.UIAbility'; 107 108 let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 109 let dataShareHelper: dataShare.DataShareHelper | undefined = undefined; 110 let context = getContext(UIAbility); 111 try { 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 128 createDataShareHelper(context: Context, uri: string, options?: DataShareHelperOptions): Promise<DataShareHelper> 129 130 Creates a **DataShareHelper** instance. This API uses a promise to return the result. 131 132 Observe the following when using this API: 133 - If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. 134 - If **exported** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. 135 - 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). 136 137 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 138 139 **Parameters** 140 141 | Name | Type | Mandatory| Description | 142 | ------- | ------------------------------------------------- | ---- | ------------------------------ | 143 | context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of the application. | 144 | uri | string | Yes | URI of the server application to connect.| 145 | 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.| 146 147 **Return value** 148 149 | Type | Description | 150 | -------------------------------------------------- | -------------------------------------- | 151 | Promise<[DataShareHelper](#datasharehelper)> | Promise used to return the **DataShareHelper** instance created.| 152 153 **Error codes** 154 155 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 156 157 | ID| Error Message | 158 | -------- | ---------------------------------------------------- | 159 | 15700010 | The DataShareHelper is not initialized successfully. | 160 161 **Example** 162 163 ```ts 164 import { BusinessError } from '@ohos.base' 165 import UIAbility from '@ohos.app.ability.UIAbility'; 166 167 let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 168 let dataShareHelper: dataShare.DataShareHelper | undefined = undefined; 169 let context = getContext(UIAbility); 170 try { 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 186 enableSilentProxy(context: Context, uri?: string): Promise<void> 187 188 Enables silent access. This API uses a promise to return the result. 189 190 Observe 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](js-apis-inner-application-context.md#context) | Yes | Context of the application. | 202 | uri | string | No | Path of the data, for which silent access is to be enabled.<br>1. If **uri** is left blank, silent access is enabled for all URIs of the data provider by default. In addition, the previous setting for a specific URI will be cleared.<br>2. If **uri** is set, silent access is enabled for the specified URI.<br>When a **datashareHelper** API is called, the URI passed in will be preferentially verified to check whether silent access is enabled. If no match is found, the system checks whether **enableSilentProxy** with an empty **uri** has been called.<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 212 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 213 214 | ID| Error Message | 215 | -------- | ---------------------------------------------------- | 216 | 15700011 | The Uri is not exist. | 217 218 **Example** 219 220 ```ts 221 import { BusinessError } from '@ohos.base' 222 import UIAbility from '@ohos.app.ability.UIAbility'; 223 224 let uri = ("datashare:///com.acts.datasharetest/entry/DB00/TBL00?Proxy=true"); 225 let context = getContext(UIAbility); 226 dataShare.enableSilentProxy(context, uri).then(() => { 227 console.info("enableSilentProxy succeed"); 228 }). catch((err: BusinessError) => { 229 console.error(`enableSilentProxy error: code: ${err.code}, message: ${err.message} `); 230 }); 231 ``` 232 233 ## dataShare.disableSilentProxy<sup>11+</sup> 234 235 disableSilentProxy(context: Context, uri?: string): Promise<void> 236 237 Disables silent access. This API uses a promise to return the result. 238 239 Observe the following when using this API: 240 - The data provider calls this API to disable silent access. 241 - 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. 242 - 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. 243 244 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 245 246 **Parameters** 247 248 | Name | Type | Mandatory| Description | 249 | ------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | 250 | context | [Context](js-apis-inner-application-context.md#context) | Yes | Context of the application. | 251 | uri | string | No | Path of the data, for which silent access is to be disabled.<br>1. If **uri** is left blank, silent access is disabled for all URIs of the data provider by default. In addition, the previous setting for a specific URI will be cleared.<br>2. If **uri** is set, silent access is disabled for the specified URI.<br>When a **datashareHelper** API is called, the URI passed in will be preferentially verified to check whether silent access is disabled. If no match is found, the system checks whether **disableSilentProxy** with an empty **uri** has been called.<br>URI format: **datashare:///{bundleName}/{moduleName}/{storeName}/{tableName}**| 252 253 **Return value** 254 255 | Type | Description | 256 | -------------------------------------------------- | -------------------------------------- | 257 | Promise<void> | returns no value.| 258 259 **Error codes** 260 261 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 262 263 | ID| Error Message | 264 | -------- | ---------------------------------------------------- | 265 | 15700011 | The Uri is not exist. | 266 267 **Example** 268 269 ```ts 270 import { BusinessError } from '@ohos.base' 271 import UIAbility from '@ohos.app.ability.UIAbility'; 272 273 let uri = ("datashare:///com.acts.datasharetest/entry/DB00/TBL00?Proxy=true"); 274 let context = getContext(UIAbility); 275 dataShare.disableSilentProxy(context, uri).then(() => { 276 console.info("disableSilentProxy succeed"); 277 }). catch((err: BusinessError) => { 278 console.error(`disableSilentProxy error: code: ${err.code}, message: ${err.message} `); 279 }); 280 ``` 281 282 ## DataShareHelperOptions<sup>10+</sup> 283 284 Defines whether [DataShareHelper](#datasharehelper) is in proxy mode. 285 286 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 287 288 | Name| Type| Mandatory| Description| 289 | -------- | -------- | -------- | -------- | 290 | 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.| 291 292 ## TemplateId<sup>10+</sup> 293 294 Defines the **TemplateId** struct. **TemplateId** is generated by [**addTemplate**](#addtemplate10) to identify a template. 295 296 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 297 298 | Name| Type| Mandatory| Description| 299 | -------- | -------- | -------- | -------- | 300 | 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.| 301 | bundleNameOfOwner | string | Yes| Bundle name of the template owner. The value must be the same as the **bundleName** in [**addTemplate**](#addtemplate10).| 302 303 ## PublishedItem<sup>10+</sup> 304 305 Defines the data to publish. 306 307 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 308 309 | Name| Type| Mandatory| Description| 310 | -------- | -------- | -------- | -------- | 311 | key | string | Yes| Key of the data to publish.| 312 | data | string \| ArrayBuffer | Yes| Data to publish. If the data to publish exceeds 20 KB, you are advised to use **data** of the ArrayBuffer type. | 313 | subscriberId | string | Yes| Subscriber ID.| 314 315 ## RdbDataChangeNode<sup>10+</sup> 316 317 Defines the subscription/unsubscription result of the RDB data changes. 318 319 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 320 321 | Name| Type| Mandatory| Description| 322 | -------- | -------- | -------- | -------- | 323 | uri | string | Yes| URI of the callback.| 324 | templateId | [TemplateId](#templateid10) | Yes| ID of the template that triggers the callback.| 325 | data | Array<string> | Yes| Data of the callback.| 326 327 ## PublishedDataChangeNode<sup>10+</sup> 328 329 Defines the subscription/unsubscription result of the changes in the published data. 330 331 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 332 333 | Name| Type| Mandatory| Description| 334 | -------- | -------- | -------- | -------- | 335 | bundleName | string | Yes| Bundle name of the callback.| 336 | data | Array<[PublishedItem](#publisheditem10)> | Yes| Data of the callback.| 337 338 ## Template<sup>10+</sup> 339 340 Defines the struct of the template used in a subscription. 341 342 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 343 344 | Name| Type| Mandatory| Description| 345 | -------- | -------- | -------- | -------- | 346 | 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. | 347 | 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.| 348 349 ## OperationResult<sup>10+</sup> 350 351 Defines the result of the operation for subscribing to or unsubscribing from the data changes or published data. 352 353 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 354 355 | Name| Type| Mandatory| Description| 356 | -------- | -------- | ----- | -------- | 357 | key | string | Yes| Key of the operation result.| 358 | result | number | Yes| Operation result. If the operation is successful, **0** is returned; otherwise, an error code is returned. | 359 ## DataShareHelper 360 361 Provides 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). 362 363 ### on('dataChange') 364 365 on(type: 'dataChange', uri: string, callback: AsyncCallback<void>): void 366 367 Subscribes to changes of the specified data. After an observer is registered, the subscriber will receive a notification when the change notification is triggered (the **notifyChange()** method is called). This API uses an asynchronous callback to return the result. 368 369 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 370 371 **Parameters** 372 373 | Name | Type | Mandatory| Description | 374 | -------- | -------------------- | ---- | ------------------------ | 375 | type | string | Yes | Event type. The value is **dataChange**, which indicates data changes. | 376 | uri | string | Yes | URI of the data.| 377 | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If data is changed, the value of **err** is undefined. Otherwise, this callback is not invoked or the value of **err** is an error object.| 378 379 **Example** 380 381 ```ts 382 let onCallback: () => void = (): void => { 383 console.info("**** Observer on callback ****"); 384 } 385 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 386 if (dataShareHelper !== undefined) { 387 (dataShareHelper as dataShare.DataShareHelper).on("dataChange", uri, onCallback); 388 } 389 ``` 390 391 ### off('dataChange') 392 393 off(type: 'dataChange', uri: string, callback?: AsyncCallback<void>): void 394 395 Unsubscribes from data changes. 396 397 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 398 399 **Parameters** 400 401 | Name | Type | Mandatory| Description | 402 | -------- | -------------------- | ---- | ------------------------ | 403 | type | string | Yes | Event type. The value is **dataChange**, which indicates data changes. | 404 | uri | string | Yes | URI of the target data.| 405 | callback | AsyncCallback<void> | No | Callback for the data change. If this parameter is left empty, all notification events of the URI will be unsubscribed from. | 406 407 **Example** 408 409 ```ts 410 let callback: () => void = (): void => { 411 console.info("**** Observer on callback ****"); 412 } 413 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 414 if (dataShareHelper != undefined) { 415 (dataShareHelper as dataShare.DataShareHelper).on("dataChange", uri, callback); 416 (dataShareHelper as dataShare.DataShareHelper).off("dataChange", uri, callback); 417 } 418 ``` 419 420 ### addTemplate<sup>10+</sup> 421 422 addTemplate(uri: string, subscriberId: string, template: Template): void 423 424 Adds a data template with the specified subscriber. 425 426 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 427 428 **Parameters** 429 430 | Name | Type | Mandatory| Description | 431 | -------- | ------------------------ | ---- | -------------------------| 432 | uri | string | Yes | URI of the data to add. | 433 | subscriberId | string | Yes | Unique ID of the template subscriber.| 434 | template | [Template](#template10) | Yes | Data template to add. | 435 436 **Error codes** 437 438 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 439 440 | ID| Error Message | 441 | -------- | -------------------- | 442 | 15700011 | The uri is not exist.| 443 444 **Example** 445 446 ```ts 447 let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 448 let subscriberId = '11'; 449 let key1: string = "p1"; 450 let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true"; 451 let key2: string = "p2"; 452 let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false"; 453 let template: dataShare.Template = { 454 predicates : { 455 key1 : value1, 456 key2 : value2, 457 }, 458 scheduler : "select remindTimer(time) from TBL00" 459 } 460 if (dataShareHelper != undefined) { 461 (dataShareHelper as dataShare.DataShareHelper).addTemplate(uri, subscriberId, template); 462 } 463 ``` 464 465 ### delTemplate<sup>10+</sup> 466 467 delTemplate(uri: string, subscriberId: string): void 468 469 Deletes a data template based on the specified subscriber. 470 471 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 472 473 **Parameters** 474 475 | Name | Type | Mandatory| Description | 476 | -------- | -------------| ---- | ------------------------- | 477 | uri | string | Yes | URI of the data to delete. | 478 | subscriberId | string | Yes | Unique ID of the subscriber. | 479 480 **Error codes** 481 482 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 483 484 | ID| Error Message | 485 | -------- | -------------------- | 486 | 15700011 | The uri is not exist.| 487 488 **Example** 489 490 ```ts 491 let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 492 let subscriberId = '11'; 493 let key1: string = "p1"; 494 let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true"; 495 let key2: string = "p2"; 496 let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false"; 497 let template: dataShare.Template = { 498 predicates : { 499 key1 : value1, 500 key2 : value2, 501 }, 502 scheduler : "select remindTimer(time) from TBL00" 503 } 504 if (dataShareHelper != undefined) { 505 (dataShareHelper as dataShare.DataShareHelper).addTemplate(uri, subscriberId, template); 506 (dataShareHelper as dataShare.DataShareHelper).delTemplate(uri, subscriberId); 507 } 508 ``` 509 510 ### on('rdbDataChange')<sup>10+</sup> 511 512 on(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback: AsyncCallback<RdbDataChangeNode>): Array<OperationResult> 513 514 Subscribes to the changes of the data corresponding to the specified URI and template. 515 516 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 517 518 **Parameters** 519 520 | Name | Type | Mandatory| Description | 521 | -------- | ----------------------------------| ---- | ------------------------------------------------------------ | 522 | type | string | Yes | Event type. The value is **rdbDataChange**, which indicates the RDB data change event. If **type** is any other value, there is no response to this API. | 523 | uris | Array<string> | Yes | URIs of the data to operate. | 524 | templateId | [TemplateId](#templateid10) | Yes | ID of the template that triggers the callback. | 525 | callback | AsyncCallback<[RdbDataChangeNode](#rdbdatachangenode10)> | Yes | Callback invoked to return the result when the specified data changes. The **err** is **undefined**, and **node** is the new data. Otherwise, this callback is not triggered or **err** is an error object. | 526 527 **Return value** 528 529 | Type | Description | 530 | ---------------- | ------------------------------------------------------------ | 531 | Array<[OperationResult](#operationresult10)> | Returns the operation result.| 532 533 **Example** 534 535 ```ts 536 import { BusinessError } from '@ohos.base' 537 538 let onCallback: (err: BusinessError, node: dataShare.RdbDataChangeNode) => void = (err: BusinessError, node:dataShare.RdbDataChangeNode): void => { 539 console.info("onCallback " + JSON.stringify(node.uri)); 540 console.info("onCallback " + JSON.stringify(node.templateId)); 541 console.info("onCallback " + node.data.length); 542 for (let i = 0; i < node.data.length; i++) { 543 console.info("onCallback " + typeof node.data[i] + " " + node.data[i]); 544 } 545 } 546 547 let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 548 let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"}; 549 if (dataShareHelper != undefined) { 550 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).on("rdbDataChange", [uri], templateId, onCallback); 551 } 552 ``` 553 554 ### off('rdbDataChange')<sup>10+</sup> 555 556 off(type: 'rdbDataChange', uris: Array<string>, templateId: TemplateId, callback?: AsyncCallback<RdbDataChangeNode>): Array<OperationResult> 557 558 Unsubscribes from the changes of the data corresponding to the specified URI and template. 559 560 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 561 562 **Parameters** 563 564 | Name | Type | Mandatory| Description | 565 | -------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | 566 | type | string | Yes | Event type. The value is **rdbDataChange**, which indicates the RDB data changes. | 567 | uris | Array<string> | Yes | URIs of the data to operate. | 568 | templateId | [TemplateId](#templateid10) | Yes | ID of the template that triggers the callback. | 569 | callback | AsyncCallback<[RdbDataChangeNode](#rdbdatachangenode10)> | No | Callback for the RDB data change. If this parameter is left empty, all notification events of the URI will be unsubscribed from. | 570 571 **Return value** 572 573 | Type | Description | 574 | ---------------- | ------------------------------------------------------------ | 575 | Array<[OperationResult](#operationresult10)> | Returns the operation result.| 576 577 **Example** 578 579 ```ts 580 let uri = ("datashareproxy://com.samples.datasharetest.DataShare"); 581 let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"}; 582 if (dataShareHelper != undefined) { 583 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).off("rdbDataChange", [uri], templateId); 584 } 585 ``` 586 587 ### on('publishedDataChange')<sup>10+</sup> 588 589 on(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, callback: AsyncCallback<PublishedDataChangeNode>): Array<OperationResult> 590 591 Subscribes to changes of the published data. 592 593 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 594 595 **Parameters** 596 597 | Name | Type | Mandatory| Description | 598 | -------- | ----------------------------------| ---- | ------------------------------------------------------------ | 599 | type | string | Yes | Event type. The value is **publishedDataChange**, which indicates the event of published data changes. | 600 | uris | Array<string> | Yes | URIs of the data to operate. | 601 | subscriberId | string | Yes | Subscriber ID of the callback. | 602 | callback | AsyncCallback<[PublishedDataChangeNode](#publisheddatachangenode10)> | Yes | Callback invoked to return the result when the published data changes. The **err** is **undefined**, and **node** is the new data. Otherwise, this callback is not triggered or **err** is an error object. | 603 604 **Return value** 605 606 | Type | Description | 607 | ---------------- | ------------------------------------------------------------ | 608 | Array<[OperationResult](#operationresult10)> | Returns the operation result.| 609 610 **Example** 611 612 ```ts 613 import { BusinessError } from '@ohos.base' 614 615 let onPublishCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => { 616 console.info("onPublishCallback node bundleName " + JSON.stringify(node.bundleName)); 617 console.info("onPublishCallback node data size" + node.data.length); 618 for (let i = 0; i < node.data.length; i++) { 619 console.info("onPublishCallback node " + typeof node.data[i].data); 620 if (typeof node.data[i].data != 'string') { 621 let array: ArrayBuffer = node.data[i].data as ArrayBuffer; 622 let data: Uint8Array = new Uint8Array(array); 623 console.info("onPublishCallback " + i + " " + JSON.stringify(data)); 624 } 625 console.info("onPublishCallback data " + i + " " + JSON.stringify(node.data[i])); 626 } 627 } 628 let uris:Array<string> = ['city', 'datashareproxy://com.acts.ohos.data.datasharetest/appInfo', 'key2']; 629 let subscriberId = '11'; 630 if (dataShareHelper != undefined) { 631 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).on('publishedDataChange', uris, subscriberId, onPublishCallback); 632 } 633 ``` 634 635 ### off('publishedDataChange')<sup>10+</sup> 636 637 off(type: 'publishedDataChange', uris: Array<string>, subscriberId: string, callback?: AsyncCallback<PublishedDataChangeNode>): Array<OperationResult> 638 639 Unsubscribes from the changes of the published data. 640 641 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 642 643 **Parameters** 644 645 | Name | Type | Mandatory| Description | 646 | -------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | 647 | type | string | Yes | Event type. The value is **publishedDataChange**, which indicates the published data changes. | 648 | uris | Array<string> | Yes | URIs of the data to operate. | 649 | subscriberId | string | Yes | Subscriber ID of the callback. | 650 | callback | AsyncCallback<[PublishedDataChangeNode](#publisheddatachangenode10)> | No | Callback for the published data change. If this parameter is left empty, all callbcks of the URI will be unregistered.| 651 652 **Return value** 653 654 | Type | Description | 655 | ---------------- | ------------------------------------------------------------ | 656 | Array<[OperationResult](#operationresult10)> | Returns the operation result.| 657 658 **Example** 659 660 ```ts 661 import { BusinessError } from '@ohos.base' 662 663 let offCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => { 664 console.info("**** Observer off callback ****"); 665 } 666 let uris:Array<string> = ["city", "datashareproxy://com.acts.ohos.data.datasharetest/appInfo", "key2"]; 667 let subscriberId = '11'; 668 if (dataShareHelper != undefined) { 669 let result: Array<dataShare.OperationResult> = (dataShareHelper as dataShare.DataShareHelper).off("publishedDataChange", uris, subscriberId, offCallback); 670 } 671 ``` 672 673 ### publish<sup>10+</sup> 674 675 publish(data: Array<PublishedItem>, bundleName: string, version: number, callback: AsyncCallback<Array<OperationResult>>): void 676 677 Publishes data to the database. 678 679 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 680 681 **Parameters** 682 683 | Name | Type | Mandatory| Description | 684 | --------- | -------------------------------------------------| ---- | ------------------- | 685 | data | Array<[PublishedItem](#publisheditem10)> | Yes | Data to publish. | 686 | 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. | 687 | 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.| 688 | callback | AsyncCallback<Array<[OperationResult](#operationresult10)>> | Yes | Callback invoked to return the result. If data is published, **err** is **undefined**, and **result** is the data publish result. Otherwise, this callback will not be triggered or **err** is an error object. | 689 690 **Error codes** 691 692 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 693 694 | ID| Error Message | 695 | -------- | -------------------------- | 696 | 15700012 | The data area is not exist.| 697 698 **Example** 699 700 ```ts 701 import { BusinessError } from '@ohos.base' 702 703 let arrayBuffer = new ArrayBuffer(1); 704 let version = 1; 705 let dataArray : Array<dataShare.PublishedItem> = [{key:"key2", subscriberId:"11", data:arrayBuffer}]; 706 let publishCallback: (err: BusinessError, result: Array<dataShare.OperationResult>) => void = (err: BusinessError, result: Array<dataShare.OperationResult>): void => { 707 console.info("publishCallback " + JSON.stringify(result)); 708 } 709 try { 710 console.info("dataArray length is:", dataArray.length); 711 if (dataShareHelper != undefined) { 712 (dataShareHelper as dataShare.DataShareHelper).publish(dataArray, "com.acts.ohos.data.datasharetest", version, publishCallback); 713 } 714 } catch (e) { 715 console.error("publish error " + JSON.stringify(e)); 716 } 717 ``` 718 719 ### publish<sup>10+</sup> 720 721 publish(data: Array<PublishedItem>, bundleName: string, callback: AsyncCallback<Array<OperationResult>>): void 722 723 Publishes data to the database. 724 725 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 726 727 **Parameters** 728 729 | Name | Type | Mandatory| Description | 730 | -------- | ------------------------------------------------- | ---- | ---------------------------------- | 731 | data | Array<[PublishedItem](#publisheditem10)> | Yes | Data to publish. | 732 | 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. | 733 | callback | AsyncCallback<Array<[OperationResult](#operationresult10)>> | Yes | Callback invoked to return the result. If data is published, **err** is **undefined**, and **result** is the data publish result. Otherwise, this callback will not be triggered or **err** is an error object.| 734 735 **Example** 736 737 **Error codes** 738 739 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 740 741 | ID| Error Message | 742 | -------- | -------------------------- | 743 | 15700012 | The data area is not exist.| 744 745 ```ts 746 import { BusinessError } from '@ohos.base' 747 748 let publishCallback: (err: BusinessError, result: Array<dataShare.OperationResult>) => void = (err: BusinessError, result: Array<dataShare.OperationResult>): void => { 749 console.info("publishCallback " + JSON.stringify(result)); 750 } 751 let dataArray : Array<dataShare.PublishedItem> = [ 752 {key:"city", subscriberId:"11", data:"xian"}, 753 {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, 754 {key:"empty", subscriberId:"11", data:"nobody sub"}]; 755 if (dataShareHelper != undefined) { 756 (dataShareHelper as dataShare.DataShareHelper).publish(dataArray, "com.acts.ohos.data.datasharetest", publishCallback); 757 } 758 ``` 759 760 ### publish<sup>10+</sup> 761 762 publish(data: Array<PublishedItem>, bundleName: string, version?: number): Promise<Array<OperationResult>> 763 764 Publishes data to the database. 765 766 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 767 768 **Parameters** 769 770 | Name | Type | Mandatory| Description | 771 | -------- | ----------------------------- | ---- | ------------------------------ | 772 | data | Array<[PublishedItem](#publisheditem10)> | Yes | Data to publish.| 773 | 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. | 774 | 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.| 775 776 **Return value** 777 778 | Type | Description | 779 | ---------------- | ------------------------------------------------------------ | 780 | Promise<Array<[OperationResult](#operationresult10)>> | Returns the operation result.| 781 782 **Error codes** 783 784 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 785 786 | ID| Error Message | 787 | -------- | -------------------------- | 788 | 15700012 | The data area is not exist.| 789 790 **Example** 791 792 ```ts 793 let dataArray: Array<dataShare.PublishedItem> = [ 794 {key:"city", subscriberId:"11", data:"xian"}, 795 {key:"datashareproxy://com.acts.ohos.data.datasharetest/appInfo", subscriberId:"11", data:"appinfo is just a test app"}, 796 {key:"empty", subscriberId:"11", data:"nobody sub"}]; 797 if (dataShareHelper != undefined) { 798 let result: Promise<Array<dataShare.OperationResult>> = (dataShareHelper as dataShare.DataShareHelper).publish(dataArray, "com.acts.ohos.data.datasharetest"); 799 } 800 ``` 801 802 ### getPublishedData<sup>10+</sup> 803 804 getPublishedData(bundleName: string, callback: AsyncCallback<Array<PublishedItem>>): void 805 806 Obtains the published data of an application. 807 808 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 809 810 **Parameters** 811 812 | Name | Type | Mandatory| Description | 813 | -------- | -----------------| ---- | ----------------------------- | 814 | bundleName | string | Yes | Application to which the data belongs. | 815 | callback | AsyncCallback<Array<[PublishedItem](#publisheditem10)>> | Yes | Callback invoked to return the published data obtained.| 816 817 **Error codes** 818 819 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 820 821 | ID| Error Message | 822 | -------- | -------------------------- | 823 | 15700012 | The data area is not exist.| 824 825 **Example** 826 827 ```ts 828 import { BusinessError } from '@ohos.base' 829 830 let publishCallback: (err: BusinessError, data: Array<dataShare.PublishedItem>) => void = (err: BusinessError, result: Array<dataShare.PublishedItem>): void => { 831 console.info("**** Observer publish callback ****"); 832 } 833 if (dataShareHelper != undefined) { 834 (dataShareHelper as dataShare.DataShareHelper).getPublishedData("com.acts.ohos.data.datasharetest", publishCallback); 835 } 836 ``` 837 838 ### getPublishedData<sup>10+</sup> 839 840 getPublishedData(bundleName: string): Promise<Array<PublishedItem>> 841 842 Obtains the published data of an application. 843 844 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 845 846 **Parameters** 847 848 | Name | Type | Mandatory| Description | 849 | -------- | --------------| ---- | -------------------------------------- | 850 | bundleName | string | Yes | Application to which the data belongs. | 851 852 **Return value** 853 854 | Type | Description | 855 | ------------------------------------------------------------ | ----------------------------------- | 856 | Promise<Array<[PublishedItem](#publisheditem10)>> | Promise used to return the published data obtained.| 857 858 **Error codes** 859 860 For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). 861 862 | ID| Error Message | 863 | -------- | -------------------------- | 864 | 15700012 | The data area is not exist.| 865 866 **Example** 867 868 ```ts 869 if (dataShareHelper != undefined) { 870 let publishedData: Promise<Array<dataShare.PublishedItem>> = (dataShareHelper as dataShare.DataShareHelper).getPublishedData("com.acts.ohos.data.datasharetest"); 871 } 872 ``` 873 874 ### insert 875 876 insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void 877 878 Inserts a single data record into the database. This API uses an asynchronous callback to return the result. 879 880 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 881 882 **Parameters** 883 884 | Name | Type | Mandatory| Description | 885 | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | 886 | uri | string | Yes | URI of the data to insert. | 887 | value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is left empty, a blank row will be inserted. | 888 | callback | AsyncCallback<number> | Yes | Callback invoked 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.| 889 890 **Example** 891 892 ```ts 893 import { ValuesBucket } from '@ohos.data.ValuesBucket' 894 import { BusinessError } from '@ohos.base' 895 896 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 897 let key1: string = "name"; 898 let value1: string = "rose"; 899 let key2: string = "age"; 900 let value2: number = 22; 901 let key3: string = "salary"; 902 let value3: number = 200.5; 903 const valueBucket: ValuesBucket = { 904 key1: value1, 905 key2: value2, 906 key3: value3, 907 } 908 try { 909 if (dataShareHelper != undefined) { 910 (dataShareHelper as dataShare.DataShareHelper).insert(uri, valueBucket, (err: BusinessError, data: number) => { 911 if (err !== undefined) { 912 console.error(`insert error: code: ${err.code}, message: ${err.message} `); 913 return; 914 } 915 console.info("insert succeed, data : " + data); 916 }); 917 } 918 } catch (err) { 919 let code = (err as BusinessError).code; 920 let message = (err as BusinessError).message; 921 console.error(`insert error: code: ${code}, message: ${message} `); 922 }; 923 ``` 924 925 ### insert 926 927 insert(uri: string, value: ValuesBucket): Promise<number> 928 929 Inserts a single data record into the database. This API uses a promise to return the result. 930 931 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 932 933 **Parameters** 934 935 | Name | Type | Mandatory| Description | 936 | ----- | --------------------------------------------------------- | ---- | -------------------------------------------------- | 937 | uri | string | Yes | URI of the data to insert. | 938 | value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is left empty, a blank row will be inserted.| 939 940 **Return value** 941 942 | Type | Description | 943 | ---------------- | ------------------------------------------------------------ | 944 | 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.| 945 946 **Example** 947 948 ```ts 949 import { BusinessError } from '@ohos.base' 950 import { ValuesBucket } from '@ohos.data.ValuesBucket' 951 952 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 953 let key1: string = "name"; 954 let value1: string = "rose1"; 955 let key2: string = "age"; 956 let value2: number = 21; 957 let key3: string = "salary"; 958 let value3: number = 20.5; 959 const valueBucket: ValuesBucket = { 960 key1: value1, 961 key2: value2, 962 key3: value3, 963 } 964 try { 965 if (dataShareHelper != undefined) { 966 (dataShareHelper as dataShare.DataShareHelper).insert(uri, valueBucket).then((data: number) => { 967 console.info("insert succeed, data : " + data); 968 }).catch((err: BusinessError) => { 969 console.error(`insert error: code: ${err.code}, message: ${err.message} `); 970 }); 971 } 972 } catch (err) { 973 let code = (err as BusinessError).code; 974 let message = (err as BusinessError).message; 975 console.error(`insert error: code: ${code}, message: ${message} `); 976 }; 977 ``` 978 979 ### delete 980 981 delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>): void 982 983 Deletes one or more data records from the database. This API uses an asynchronous callback to return the result. 984 985 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 986 987 **Parameters** 988 989 | Name | Type | Mandatory| Description | 990 | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 991 | uri | string | Yes | URI of the data to delete. | 992 | 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.| 993 | callback | AsyncCallback<number> | Yes | Callback invoked 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.| 994 995 **Example** 996 997 ```ts 998 import dataSharePredicates from '@ohos.data.dataSharePredicates'; 999 import { BusinessError } from '@ohos.base' 1000 1001 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1002 let da = new dataSharePredicates.DataSharePredicates(); 1003 da.equalTo("name", "ZhangSan"); 1004 try { 1005 if (dataShareHelper != undefined) { 1006 (dataShareHelper as dataShare.DataShareHelper).delete(uri, da, (err: BusinessError, data: number) => { 1007 if (err !== undefined) { 1008 console.error(`delete error: code: ${err.code}, message: ${err.message} `); 1009 return; 1010 } 1011 console.info("delete succeed, data : " + data); 1012 }); 1013 } 1014 } catch (err) { 1015 let code = (err as BusinessError).code; 1016 let message = (err as BusinessError).message; 1017 console.error(`delete error: code: ${code}, message: ${message} `); 1018 }; 1019 ``` 1020 1021 ### delete 1022 1023 delete(uri: string, predicates: dataSharePredicates.DataSharePredicates): Promise<number> 1024 1025 Deletes one or more data records from the database. This API uses a promise to return the result. 1026 1027 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1028 1029 **Parameters** 1030 1031 | Name | Type | Mandatory| Description | 1032 | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1033 | uri | string | Yes | URI of the data to delete. | 1034 | 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.| 1035 1036 **Return value** 1037 1038 | Type | Description | 1039 | ---------------- | ------------------------------------------------------------ | 1040 | 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.| 1041 1042 **Example** 1043 1044 ```ts 1045 import dataSharePredicates from '@ohos.data.dataSharePredicates'; 1046 import { BusinessError } from '@ohos.base' 1047 1048 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1049 let da = new dataSharePredicates.DataSharePredicates(); 1050 da.equalTo("name", "ZhangSan"); 1051 try { 1052 if (dataShareHelper != undefined) { 1053 (dataShareHelper as dataShare.DataShareHelper).delete(uri, da).then((data: number) => { 1054 console.info("delete succeed, data : " + data); 1055 }).catch((err: BusinessError) => { 1056 console.error(`delete error: code: ${err.code}, message: ${err.message} `); 1057 }); 1058 } 1059 } catch (err) { 1060 let code = (err as BusinessError).code; 1061 let message = (err as BusinessError).message; 1062 console.error(`delete error: code: ${code}, message: ${message} `); 1063 }; 1064 ``` 1065 1066 ### query 1067 1068 query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void 1069 1070 Queries data in the database. This API uses an asynchronous callback to return the result. 1071 1072 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1073 1074 **Parameters** 1075 1076 | Name | Type | Mandatory| Description | 1077 | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1078 | uri | string | Yes | URI of the data to query. | 1079 | 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.| 1080 | columns | Array<string> | Yes | Column to query. If this parameter is left empty, all columns will be queried. | 1081 | callback | AsyncCallback<[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)> | Yes | Callback invoked 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.| 1082 1083 **Example** 1084 1085 ```ts 1086 import dataSharePredicates from '@ohos.data.dataSharePredicates'; 1087 import { BusinessError } from '@ohos.base' 1088 import DataShareResultSet from '@ohos.data.DataShareResultSet' 1089 1090 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1091 let columns = ["*"]; 1092 let da = new dataSharePredicates.DataSharePredicates(); 1093 da.equalTo("name", "ZhangSan"); 1094 try { 1095 if (dataShareHelper != undefined) { 1096 (dataShareHelper as dataShare.DataShareHelper).query(uri, da, columns, (err: BusinessError, data: DataShareResultSet) => { 1097 if (err !== undefined) { 1098 console.error(`query error: code: ${err.code}, message: ${err.message} `); 1099 return; 1100 } 1101 console.info("query succeed, rowCount : " + data.rowCount); 1102 }); 1103 } 1104 } catch (err) { 1105 let code = (err as BusinessError).code; 1106 let message = (err as BusinessError).message; 1107 console.error(`query error: code: ${code}, message: ${message} `); 1108 }; 1109 ``` 1110 1111 ### query 1112 1113 query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>): Promise<DataShareResultSet> 1114 1115 Queries data in the database. This API uses a promise to return the result. 1116 1117 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1118 1119 **Parameters** 1120 1121 | Name | Type | Mandatory| Description | 1122 | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1123 | uri | string | Yes | URI of the data to query. | 1124 | 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.| 1125 | columns | Array<string> | Yes | Column to query. If this parameter is left empty, all columns will be queried. | 1126 1127 **Return value** 1128 1129 | Type | Description | 1130 | ------------------------------------------------------------ | --------------------------------- | 1131 | Promise<[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)> | Promise used to return the result set obtained.| 1132 1133 **Example** 1134 1135 ```ts 1136 import dataSharePredicates from '@ohos.data.dataSharePredicates'; 1137 import { BusinessError } from '@ohos.base' 1138 import DataShareResultSet from '@ohos.data.DataShareResultSet' 1139 1140 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1141 let columns = ["*"]; 1142 let da = new dataSharePredicates.DataSharePredicates(); 1143 da.equalTo("name", "ZhangSan"); 1144 try { 1145 if (dataShareHelper != undefined) { 1146 (dataShareHelper as dataShare.DataShareHelper).query(uri, da, columns).then((data: DataShareResultSet) => { 1147 console.info("query succeed, rowCount : " + data.rowCount); 1148 }).catch((err: BusinessError) => { 1149 console.error(`query error: code: ${err.code}, message: ${err.message} `); 1150 }); 1151 } 1152 } catch (err) { 1153 let code = (err as BusinessError).code; 1154 let message = (err as BusinessError).message; 1155 console.error(`query error: code: ${code}, message: ${message} `); 1156 }; 1157 ``` 1158 1159 ### update 1160 1161 update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void 1162 1163 Updates data in the database. This API uses an asynchronous callback to return the result. 1164 1165 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1166 1167 **Parameters** 1168 1169 | Name | Type | Mandatory| Description | 1170 | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1171 | uri | string | Yes | URI of the data to update. | 1172 | 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.| 1173 | value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data, which can be null. | 1174 | callback | AsyncCallback<number> | Yes | Callback invoked 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.| 1175 1176 **Example** 1177 1178 ```ts 1179 import dataSharePredicates from '@ohos.data.dataSharePredicates'; 1180 import { BusinessError } from '@ohos.base' 1181 import { ValuesBucket } from '@ohos.data.ValuesBucket' 1182 1183 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1184 let da = new dataSharePredicates.DataSharePredicates(); 1185 da.equalTo("name", "ZhangSan"); 1186 let key1: string = "name"; 1187 let value1: string = "roe1" 1188 let key2: string = "age"; 1189 let value2: number = 21 1190 let key3: string = "salary"; 1191 let value3: number = 20.5; 1192 const va: ValuesBucket = { 1193 key1: value1, 1194 key2: value2, 1195 key3: value3, 1196 } 1197 try { 1198 if (dataShareHelper != undefined) { 1199 (dataShareHelper as dataShare.DataShareHelper).update(uri, da, va, (err: BusinessError, data: number) => { 1200 if (err !== undefined) { 1201 console.error(`update error: code: ${err.code}, message: ${err.message} `); 1202 return; 1203 } 1204 console.info("update succeed, data : " + data); 1205 }); 1206 } 1207 } catch (err) { 1208 let code = (err as BusinessError).code; 1209 let message = (err as BusinessError).message; 1210 console.error(`update error: code: ${code}, message: ${message} `); 1211 }; 1212 ``` 1213 1214 ### update 1215 1216 update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket): Promise<number> 1217 1218 Updates data in the database. This API uses a promise to return the result. 1219 1220 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1221 1222 **Parameters** 1223 1224 | Name | Type | Mandatory| Description | 1225 | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1226 | uri | string | Yes | URI of the data to update. | 1227 | 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.| 1228 | value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data, which can be null. | 1229 1230 **Return value** 1231 1232 | Type | Description | 1233 | ---------------- | ------------------------------------------------------------ | 1234 | 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.| 1235 1236 **Example** 1237 1238 ```ts 1239 import dataSharePredicates from '@ohos.data.dataSharePredicates'; 1240 import { ValuesBucket } from '@ohos.data.ValuesBucket' 1241 import { BusinessError } from '@ohos.base' 1242 1243 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1244 let da = new dataSharePredicates.DataSharePredicates(); 1245 da.equalTo("name", "ZhangSan"); 1246 let key1: string = "name"; 1247 let value1: string = "roe1" 1248 let key2: string = "age"; 1249 let value2: number = 21 1250 let key3: string = "salary"; 1251 let value3: number = 20.5; 1252 const va: ValuesBucket = { 1253 key1: value1, 1254 key2: value2, 1255 key3: value3, 1256 } 1257 try { 1258 if (dataShareHelper != undefined) { 1259 (dataShareHelper as dataShare.DataShareHelper).update(uri, da, va).then((data: number) => { 1260 console.info("update succeed, data : " + data); 1261 }).catch((err: BusinessError) => { 1262 console.error(`update error: code: ${err.code}, message: ${err.message} `); 1263 }); 1264 } 1265 } catch (err) { 1266 let code = (err as BusinessError).code; 1267 let message = (err as BusinessError).message; 1268 console.error(`update error: code: ${code}, message: ${message} `); 1269 }; 1270 ``` 1271 1272 ### batchInsert 1273 1274 batchInsert(uri: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>): void 1275 1276 Batch inserts data into the database. This API uses an asynchronous callback to return the result. Silent access is not supported currently. 1277 1278 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1279 1280 **Parameters** 1281 1282 | Name | Type | Mandatory| Description | 1283 | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | 1284 | uri | string | Yes | URI of the data to insert. | 1285 | values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | 1286 | callback | AsyncCallback<number> | Yes | Callback invoked 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.| 1287 1288 **Example** 1289 1290 ```ts 1291 import { ValuesBucket } from '@ohos.data.ValuesBucket' 1292 import { BusinessError } from '@ohos.base' 1293 1294 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1295 let key1: string = "name"; 1296 let value11: string = "roe11" 1297 let key2: string = "age"; 1298 let value21: number = 21; 1299 let key3: string = "salary"; 1300 let value31: number = 20.5; 1301 let valuesBucket1: ValuesBucket = { 1302 key1: value11, 1303 key2: value21, 1304 key3: value31, 1305 } 1306 let vbs = new Array(valuesBucket1); 1307 try { 1308 if (dataShareHelper != undefined) { 1309 (dataShareHelper as dataShare.DataShareHelper).batchInsert(uri, vbs, (err, data) => { 1310 if (err !== undefined) { 1311 console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); 1312 return; 1313 } 1314 console.info("batchInsert succeed, data : " + data); 1315 }); 1316 } 1317 } catch (err) { 1318 let code = (err as BusinessError).code; 1319 let message = (err as BusinessError).message; 1320 console.error(`batchInsert error: code: ${code}, message: ${message} `); 1321 }; 1322 ``` 1323 1324 ### batchInsert 1325 1326 batchInsert(uri: string, values: Array<ValuesBucket>): Promise<number> 1327 1328 Batch inserts data into the database. This API uses a promise to return the result. Silent access is not supported currently. 1329 1330 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1331 1332 **Parameters** 1333 1334 | Name | Type | Mandatory| Description | 1335 | ------ | ------------------------------------------------------------ | ---- | ------------------------ | 1336 | uri | string | Yes | URI of the data to insert.| 1337 | values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | 1338 1339 **Return value** 1340 1341 | Type | Description | 1342 | ---------------- | ------------------------------------------------------------ | 1343 | 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.| 1344 1345 **Example** 1346 1347 ```ts 1348 import { ValuesBucket } from '@ohos.data.ValuesBucket' 1349 import { BusinessError } from '@ohos.base' 1350 1351 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1352 let key1: string = "name"; 1353 let value11: string = "roe11" 1354 let key2: string = "age"; 1355 let value21: number = 21; 1356 let key3: string = "salary"; 1357 let value31: number = 20.5; 1358 let valuesBucket1: ValuesBucket = { 1359 key1: value11, 1360 key2: value21, 1361 key3: value31, 1362 } 1363 let vbs = new Array(valuesBucket1); 1364 try { 1365 if (dataShareHelper != undefined) { 1366 (dataShareHelper as dataShare.DataShareHelper).batchInsert(uri, vbs).then((data: number) => { 1367 console.info("batchInsert succeed, data : " + data); 1368 }).catch((err: BusinessError) => { 1369 console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); 1370 }); 1371 } 1372 } catch (err) { 1373 let code = (err as BusinessError).code; 1374 let message = (err as BusinessError).message 1375 console.error(`batchInsert error: code: ${code}, message: ${message} `); 1376 }; 1377 ``` 1378 1379 ### normalizeUri 1380 1381 normalizeUri(uri: string, callback: AsyncCallback<string>): void 1382 1383 Normalizes 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. 1384 1385 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1386 1387 **Parameters** 1388 1389 | Name | Type | Mandatory| Description | 1390 | -------- | ---------------------- | ---- | -------------------------------------------------------- | 1391 | uri | string | Yes | [URI](js-apis-uri.md#uri) to normalize. | 1392 | callback | AsyncCallback<string> | Yes | Callback invoked 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.| 1393 1394 **Example** 1395 1396 ```ts 1397 import { BusinessError } from '@ohos.base' 1398 1399 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1400 if (dataShareHelper != undefined) { 1401 (dataShareHelper as dataShare.DataShareHelper).normalizeUri(uri, (err: BusinessError, data: string) => { 1402 if (err !== undefined) { 1403 console.info("normalizeUri failed, error message : " + err); 1404 } else { 1405 console.info("normalizeUri = " + data); 1406 } 1407 }); 1408 } 1409 ``` 1410 1411 ### normalizeUri 1412 1413 normalizeUri(uri: string): Promise<string> 1414 1415 Normalizes 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. 1416 1417 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1418 1419 **Parameters** 1420 1421 | Name| Type | Mandatory| Description | 1422 | ---- | ------ | ---- | ----------------------------------------- | 1423 | uri | string | Yes | [URI](js-apis-uri.md#uri) to normalize.| 1424 1425 **Return value** 1426 1427 | Type | Description | 1428 | ---------------- | ---------------------------------------------- | 1429 | Promise<string> | Promise used to return the result. If URI normalization is supported, the normalized URI is returned. Otherwise, **null** is returned.| 1430 1431 **Example** 1432 1433 ```ts 1434 import { BusinessError } from '@ohos.base' 1435 1436 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1437 if (dataShareHelper != undefined) { 1438 (dataShareHelper as dataShare.DataShareHelper).normalizeUri(uri).then((data: string) => { 1439 console.info("normalizeUri = " + data); 1440 }).catch((err: BusinessError) => { 1441 console.info("normalizeUri failed, error message : " + err); 1442 }); 1443 } 1444 ``` 1445 1446 ### denormalizeUri 1447 1448 denormalizeUri(uri: string, callback: AsyncCallback<string>): void 1449 1450 Denormalizes a URI. This API uses an asynchronous callback to return the result. Silent access is not supported currently. 1451 1452 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1453 1454 **Parameters** 1455 1456 | Name | Type | Mandatory| Description | 1457 | -------- | ---------------------- | ---- | --------------------------------------------------- | 1458 | uri | string | Yes | [URI](js-apis-uri.md#uri) to denormalize.| 1459 | callback | AsyncCallback<string> | Yes | Callback invoked 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.| 1460 1461 **Example** 1462 1463 ```ts 1464 import { BusinessError } from '@ohos.base' 1465 1466 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1467 if (dataShareHelper != undefined) { 1468 (dataShareHelper as dataShare.DataShareHelper).denormalizeUri(uri, (err: BusinessError, data: string) => { 1469 if (err !== undefined) { 1470 console.error("denormalizeUri failed, error message : " + err); 1471 } else { 1472 console.info("denormalizeUri = " + data); 1473 } 1474 }); 1475 } 1476 ``` 1477 1478 ### denormalizeUri 1479 1480 denormalizeUri(uri: string): Promise<string> 1481 1482 Denormalizes a URI. This API uses a promise to return the result. Silent access is not supported currently. 1483 1484 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1485 1486 **Parameters** 1487 1488 | Name| Type | Mandatory| Description | 1489 | ---- | ------ | ---- | ------------------------------------------- | 1490 | uri | string | Yes | [URI](js-apis-uri.md#uri) to denormalize.| 1491 1492 **Return value** 1493 1494 | Type | Description | 1495 | ---------------- | ----------------------------------------- | 1496 | 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.| 1497 1498 **Example** 1499 1500 ```ts 1501 import { BusinessError } from '@ohos.base' 1502 1503 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1504 if (dataShareHelper != undefined) { 1505 (dataShareHelper as dataShare.DataShareHelper).denormalizeUri(uri).then((data: string) => { 1506 console.info("denormalizeUri = " + data); 1507 }).catch((err: BusinessError) => { 1508 console.error("denormalizeUri failed, error message : " + err); 1509 }); 1510 } 1511 ``` 1512 1513 ### notifyChange 1514 1515 notifyChange(uri: string, callback: AsyncCallback<void>): void 1516 1517 Notifies the registered observer of data changes. This API uses an asynchronous callback to return the result. Silent access is not supported currently. 1518 1519 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1520 1521 **Parameters** 1522 1523 | Name | Type | Mandatory| Description | 1524 | -------- | -------------------- | ---- | ------------------------ | 1525 | uri | string | Yes | URI of the data.| 1526 | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the observer is notified of the data changes, **err** is **undefined**. Otherwise, **err** is an error object.| 1527 1528 **Example** 1529 1530 ```ts 1531 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1532 if (dataShareHelper != undefined) { 1533 (dataShareHelper as dataShare.DataShareHelper).notifyChange(uri, () => { 1534 console.info("***** notifyChange *****"); 1535 }); 1536 } 1537 ``` 1538 1539 ### notifyChange 1540 1541 notifyChange(uri: string): Promise<void> 1542 1543 Notifies the registered observer of data changes. This API uses a promise to return the result. Silent access is not supported currently. 1544 1545 **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer 1546 1547 **Parameters** 1548 1549 | Name| Type | Mandatory| Description | 1550 | ---- | ------ | ---- | -------------------- | 1551 | uri | string | Yes | URI of the data.| 1552 1553 **Return value** 1554 1555 | Type | Description | 1556 | -------------- | --------------------- | 1557 | Promise<void> | Promise that returns no value.| 1558 1559 **Example** 1560 1561 ```ts 1562 let uri = ("datashare:///com.samples.datasharetest.DataShare"); 1563 if (dataShareHelper != undefined) { 1564 (dataShareHelper as dataShare.DataShareHelper).notifyChange(uri); 1565 } 1566 ``` 1567