• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.data.dataShare (Data Sharing)
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 '@ohos.data.dataShare'
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
26Observe 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
43For 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
52import { BusinessError } from '@ohos.base'
53import UIAbility from '@ohos.app.ability.UIAbility';
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&lt;DataShareHelper&gt;): void
76
77Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result.
78
79Observe 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&lt;[DataShareHelper](#datasharehelper)&gt; | 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
96For 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
105import { BusinessError } from '@ohos.base'
106import UIAbility from '@ohos.app.ability.UIAbility';
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&lt;DataShareHelper&gt;
129
130Creates a **DataShareHelper** instance. This API uses a promise to return the result.
131
132Observe 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&lt;[DataShareHelper](#datasharehelper)&gt; | Promise used to return the **DataShareHelper** instance created.|
152
153**Error codes**
154
155For 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
164import { BusinessError } from '@ohos.base'
165import UIAbility from '@ohos.app.ability.UIAbility';
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&lt;void&gt;
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](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&lt;void&gt; | returns no value.|
209
210**Error codes**
211
212For 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
221import { BusinessError } from '@ohos.base'
222import UIAbility from '@ohos.app.ability.UIAbility';
223
224let uri = ("datashare:///com.acts.datasharetest/entry/DB00/TBL00?Proxy=true");
225let context = getContext(UIAbility);
226dataShare.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
235disableSilentProxy(context: Context, uri?: string): Promise&lt;void&gt;
236
237Disables silent access. This API uses a promise to return the result.
238
239Observe 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&lt;void&gt; | returns no value.|
258
259**Error codes**
260
261For 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
270import { BusinessError } from '@ohos.base'
271import UIAbility from '@ohos.app.ability.UIAbility';
272
273let uri = ("datashare:///com.acts.datasharetest/entry/DB00/TBL00?Proxy=true");
274let context = getContext(UIAbility);
275dataShare.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
284Defines 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
294Defines 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
305Defines 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
317Defines 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&lt;string&gt; | Yes| Data of the callback.|
326
327## PublishedDataChangeNode<sup>10+</sup>
328
329Defines 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&lt;[PublishedItem](#publisheditem10)&gt; | Yes| Data of the callback.|
337
338## Template<sup>10+</sup>
339
340Defines 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
351Defines 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
361Provides 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
365on(type: 'dataChange', uri: string, callback: AsyncCallback&lt;void&gt;): void
366
367Subscribes 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&lt;void&gt; | 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
382let onCallback: () => void = (): void => {
383  console.info("**** Observer on callback ****");
384}
385let uri = ("datashare:///com.samples.datasharetest.DataShare");
386if (dataShareHelper !== undefined) {
387  (dataShareHelper as dataShare.DataShareHelper).on("dataChange", uri, onCallback);
388}
389```
390
391### off('dataChange')
392
393off(type: 'dataChange', uri: string, callback?: AsyncCallback&lt;void&gt;): void
394
395Unsubscribes 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&lt;void&gt; | 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
410let callback: () => void = (): void => {
411  console.info("**** Observer on callback ****");
412}
413let uri = ("datashare:///com.samples.datasharetest.DataShare");
414if (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
422addTemplate(uri: string, subscriberId: string, template: Template): void
423
424Adds 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
438For 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
447let uri = ("datashareproxy://com.samples.datasharetest.DataShare");
448let subscriberId = '11';
449let key1: string = "p1";
450let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true";
451let key2: string = "p2";
452let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false";
453let template: dataShare.Template = {
454  predicates : {
455    key1 : value1,
456    key2 : value2,
457  },
458  scheduler : "select remindTimer(time) from TBL00"
459}
460if (dataShareHelper != undefined) {
461  (dataShareHelper as dataShare.DataShareHelper).addTemplate(uri, subscriberId, template);
462}
463```
464
465### delTemplate<sup>10+</sup>
466
467delTemplate(uri: string, subscriberId: string): void
468
469Deletes 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
482For 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
491let uri = ("datashareproxy://com.samples.datasharetest.DataShare");
492let subscriberId = '11';
493let key1: string = "p1";
494let value1: string = "select cityColumn as city_1, visitedCilumn as visited_1 from citys where like = true";
495let key2: string = "p2";
496let value2: string = "select cityColumn as city_2, visitedCilumn as visited_2 from citys where like = false";
497let template: dataShare.Template = {
498  predicates : {
499    key1 : value1,
500    key2 : value2,
501  },
502  scheduler : "select remindTimer(time) from TBL00"
503}
504if (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
512on(type: 'rdbDataChange', uris: Array&lt;string&gt;, templateId: TemplateId, callback: AsyncCallback&lt;RdbDataChangeNode&gt;): Array&lt;OperationResult&gt;
513
514Subscribes 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&lt;string&gt;                | Yes  | URIs of the data to operate.          |
524| templateId | [TemplateId](#templateid10)       | Yes  | ID of the template that triggers the callback.          |
525| callback | AsyncCallback&lt;[RdbDataChangeNode](#rdbdatachangenode10)&gt;   | 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&lt;[OperationResult](#operationresult10)&gt; | Returns the operation result.|
532
533**Example**
534
535```ts
536import { BusinessError } from '@ohos.base'
537
538let 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
547let uri = ("datashareproxy://com.samples.datasharetest.DataShare");
548let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"};
549if (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
556off(type: 'rdbDataChange', uris: Array&lt;string&gt;, templateId: TemplateId, callback?: AsyncCallback&lt;RdbDataChangeNode&gt;): Array&lt;OperationResult&gt;
557
558Unsubscribes 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&lt;string&gt;                           | Yes  | URIs of the data to operate.          |
568| templateId | [TemplateId](#templateid10)                | Yes  | ID of the template that triggers the callback.       |
569| callback | AsyncCallback&lt;[RdbDataChangeNode](#rdbdatachangenode10)&gt; | 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&lt;[OperationResult](#operationresult10)&gt; | Returns the operation result.|
576
577**Example**
578
579```ts
580let uri = ("datashareproxy://com.samples.datasharetest.DataShare");
581let templateId:dataShare.TemplateId = {subscriberId:"11", bundleNameOfOwner:"com.acts.ohos.data.datasharetest"};
582if (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
589on(type: 'publishedDataChange', uris: Array&lt;string&gt;, subscriberId: string, callback: AsyncCallback&lt;PublishedDataChangeNode&gt;): Array&lt;OperationResult&gt;
590
591Subscribes 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&lt;string&gt;                | Yes  | URIs of the data to operate.          |
601| subscriberId | string                        | Yes  | Subscriber ID of the callback.          |
602| callback | AsyncCallback&lt;[PublishedDataChangeNode](#publisheddatachangenode10)&gt;   | 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&lt;[OperationResult](#operationresult10)&gt; | Returns the operation result.|
609
610**Example**
611
612```ts
613import { BusinessError } from '@ohos.base'
614
615let 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}
628let uris:Array<string> = ['city', 'datashareproxy://com.acts.ohos.data.datasharetest/appInfo', 'key2'];
629let subscriberId = '11';
630if (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
637off(type: 'publishedDataChange', uris: Array&lt;string&gt;, subscriberId: string, callback?: AsyncCallback&lt;PublishedDataChangeNode&gt;): Array&lt;OperationResult&gt;
638
639Unsubscribes 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&lt;string&gt;                           | Yes  | URIs of the data to operate.          |
649| subscriberId | string                                   | Yes  | Subscriber ID of the callback.          |
650| callback | AsyncCallback&lt;[PublishedDataChangeNode](#publisheddatachangenode10)&gt; | 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&lt;[OperationResult](#operationresult10)&gt; | Returns the operation result.|
657
658**Example**
659
660```ts
661import { BusinessError } from '@ohos.base'
662
663let offCallback: (err: BusinessError, node: dataShare.PublishedDataChangeNode) => void = (err: BusinessError, node:dataShare.PublishedDataChangeNode): void => {
664  console.info("**** Observer off callback ****");
665}
666let uris:Array<string> = ["city", "datashareproxy://com.acts.ohos.data.datasharetest/appInfo", "key2"];
667let subscriberId = '11';
668if (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
675publish(data: Array&lt;PublishedItem&gt;, bundleName: string, version: number, callback: AsyncCallback&lt;Array&lt;OperationResult&gt;&gt;): void
676
677Publishes 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&lt;[PublishedItem](#publisheditem10)&gt;     | 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&lt;Array&lt;[OperationResult](#operationresult10)&gt;&gt; | 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
692For 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
701import { BusinessError } from '@ohos.base'
702
703let arrayBuffer = new ArrayBuffer(1);
704let version = 1;
705let dataArray : Array<dataShare.PublishedItem> = [{key:"key2", subscriberId:"11", data:arrayBuffer}];
706let publishCallback: (err: BusinessError, result: Array<dataShare.OperationResult>) => void = (err: BusinessError, result: Array<dataShare.OperationResult>): void => {
707  console.info("publishCallback " + JSON.stringify(result));
708}
709try {
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
721publish(data: Array&lt;PublishedItem&gt;, bundleName: string, callback: AsyncCallback&lt;Array&lt;OperationResult&gt;&gt;): void
722
723Publishes 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&lt;[PublishedItem](#publisheditem10)&gt;                        | 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&lt;Array&lt;[OperationResult](#operationresult10)&gt;&gt; | 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
739For 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
746import { BusinessError } from '@ohos.base'
747
748let publishCallback: (err: BusinessError, result: Array<dataShare.OperationResult>) => void = (err: BusinessError, result: Array<dataShare.OperationResult>): void => {
749  console.info("publishCallback " + JSON.stringify(result));
750}
751let 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"}];
755if (dataShareHelper != undefined) {
756  (dataShareHelper as dataShare.DataShareHelper).publish(dataArray, "com.acts.ohos.data.datasharetest", publishCallback);
757}
758```
759
760### publish<sup>10+</sup>
761
762publish(data: Array&lt;PublishedItem&gt;, bundleName: string, version?: number): Promise&lt;Array&lt;OperationResult&gt;&gt;
763
764Publishes 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&lt;[PublishedItem](#publisheditem10)&gt;    | 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&lt;Array&lt;[OperationResult](#operationresult10)&gt;&gt; | Returns the operation result.|
781
782**Error codes**
783
784For 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
793let 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"}];
797if (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
804getPublishedData(bundleName: string, callback: AsyncCallback&lt;Array&lt;PublishedItem&gt;&gt;): void
805
806Obtains 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&lt;Array&lt;[PublishedItem](#publisheditem10)&gt;&gt; | Yes  | Callback invoked to return the published data obtained.|
816
817**Error codes**
818
819For 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
828import { BusinessError } from '@ohos.base'
829
830let publishCallback: (err: BusinessError, data: Array<dataShare.PublishedItem>) => void = (err: BusinessError, result: Array<dataShare.PublishedItem>): void => {
831  console.info("**** Observer publish callback ****");
832}
833if (dataShareHelper != undefined) {
834  (dataShareHelper as dataShare.DataShareHelper).getPublishedData("com.acts.ohos.data.datasharetest", publishCallback);
835}
836```
837
838### getPublishedData<sup>10+</sup>
839
840getPublishedData(bundleName: string): Promise&lt;Array&lt;PublishedItem&gt;&gt;
841
842Obtains 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&lt;Array&lt;[PublishedItem](#publisheditem10)&gt;&gt; | Promise used to return the published data obtained.|
857
858**Error codes**
859
860For 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
869if (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
876insert(uri: string, value: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void
877
878Inserts 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&lt;number&gt;                               | 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
893import { ValuesBucket } from '@ohos.data.ValuesBucket'
894import { BusinessError } from '@ohos.base'
895
896let uri = ("datashare:///com.samples.datasharetest.DataShare");
897let key1: string = "name";
898let value1: string = "rose";
899let key2: string = "age";
900let value2: number = 22;
901let key3: string = "salary";
902let value3: number = 200.5;
903const valueBucket: ValuesBucket = {
904  key1: value1,
905  key2: value2,
906  key3: value3,
907}
908try {
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
927insert(uri: string, value: ValuesBucket): Promise&lt;number&gt;
928
929Inserts 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&lt;number&gt; | 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
949import { BusinessError } from '@ohos.base'
950import { ValuesBucket } from '@ohos.data.ValuesBucket'
951
952let uri = ("datashare:///com.samples.datasharetest.DataShare");
953let key1: string = "name";
954let value1: string = "rose1";
955let key2: string = "age";
956let value2: number = 21;
957let key3: string = "salary";
958let value3: number = 20.5;
959const valueBucket: ValuesBucket = {
960  key1: value1,
961  key2: value2,
962  key3: value3,
963}
964try {
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
981delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;): void
982
983Deletes 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&lt;number&gt;                                  | 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
998import dataSharePredicates from '@ohos.data.dataSharePredicates';
999import { BusinessError } from '@ohos.base'
1000
1001let uri = ("datashare:///com.samples.datasharetest.DataShare");
1002let da = new dataSharePredicates.DataSharePredicates();
1003da.equalTo("name", "ZhangSan");
1004try {
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
1023delete(uri: string, predicates: dataSharePredicates.DataSharePredicates): Promise&lt;number&gt;
1024
1025Deletes 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&lt;number&gt; | 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
1045import dataSharePredicates from '@ohos.data.dataSharePredicates';
1046import { BusinessError } from '@ohos.base'
1047
1048let uri = ("datashare:///com.samples.datasharetest.DataShare");
1049let da = new dataSharePredicates.DataSharePredicates();
1050da.equalTo("name", "ZhangSan");
1051try {
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
1068query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;DataShareResultSet&gt;): void
1069
1070Queries 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&lt;string&gt;                                          | Yes  | Column to query. If this parameter is left empty, all columns will be queried.              |
1081| callback   | AsyncCallback&lt;[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)&gt; | 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
1086import dataSharePredicates from '@ohos.data.dataSharePredicates';
1087import { BusinessError } from '@ohos.base'
1088import DataShareResultSet from '@ohos.data.DataShareResultSet'
1089
1090let uri = ("datashare:///com.samples.datasharetest.DataShare");
1091let columns = ["*"];
1092let da = new dataSharePredicates.DataSharePredicates();
1093da.equalTo("name", "ZhangSan");
1094try {
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
1113query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array&lt;string&gt;): Promise&lt;DataShareResultSet&gt;
1114
1115Queries 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&lt;string&gt;                                          | 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&lt;[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)&gt; | Promise used to return the result set obtained.|
1132
1133**Example**
1134
1135```ts
1136import dataSharePredicates from '@ohos.data.dataSharePredicates';
1137import { BusinessError } from '@ohos.base'
1138import DataShareResultSet from '@ohos.data.DataShareResultSet'
1139
1140let uri = ("datashare:///com.samples.datasharetest.DataShare");
1141let columns = ["*"];
1142let da = new dataSharePredicates.DataSharePredicates();
1143da.equalTo("name", "ZhangSan");
1144try {
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
1161update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void
1162
1163Updates 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&lt;number&gt;                                  | 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
1179import dataSharePredicates from '@ohos.data.dataSharePredicates';
1180import { BusinessError } from '@ohos.base'
1181import { ValuesBucket } from '@ohos.data.ValuesBucket'
1182
1183let uri = ("datashare:///com.samples.datasharetest.DataShare");
1184let da = new dataSharePredicates.DataSharePredicates();
1185da.equalTo("name", "ZhangSan");
1186let key1: string = "name";
1187let value1: string = "roe1"
1188let key2: string = "age";
1189let value2: number = 21
1190let key3: string = "salary";
1191let value3: number = 20.5;
1192const va: ValuesBucket = {
1193  key1: value1,
1194  key2: value2,
1195  key3: value3,
1196}
1197try {
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
1216update(uri: string, predicates: dataSharePredicates.DataSharePredicates, value: ValuesBucket): Promise&lt;number&gt;
1217
1218Updates 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&lt;number&gt; | 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
1239import dataSharePredicates from '@ohos.data.dataSharePredicates';
1240import { ValuesBucket } from '@ohos.data.ValuesBucket'
1241import { BusinessError } from '@ohos.base'
1242
1243let uri = ("datashare:///com.samples.datasharetest.DataShare");
1244let da = new dataSharePredicates.DataSharePredicates();
1245da.equalTo("name", "ZhangSan");
1246let key1: string = "name";
1247let value1: string = "roe1"
1248let key2: string = "age";
1249let value2: number = 21
1250let key3: string = "salary";
1251let value3: number = 20.5;
1252const va: ValuesBucket = {
1253  key1: value1,
1254  key2: value2,
1255  key3: value3,
1256}
1257try {
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
1274batchInsert(uri: string, values: Array&lt;ValuesBucket&gt;, callback: AsyncCallback&lt;number&gt;): void
1275
1276Batch 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&lt;[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)&gt; | Yes  | Data to insert.                                          |
1286| callback | AsyncCallback&lt;number&gt;                                  | 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
1291import { ValuesBucket } from '@ohos.data.ValuesBucket'
1292import { BusinessError } from '@ohos.base'
1293
1294let uri = ("datashare:///com.samples.datasharetest.DataShare");
1295let key1: string = "name";
1296let value11: string = "roe11"
1297let key2: string = "age";
1298let value21: number = 21;
1299let key3: string = "salary";
1300let value31: number = 20.5;
1301let valuesBucket1: ValuesBucket = {
1302  key1: value11,
1303  key2: value21,
1304  key3: value31,
1305}
1306let vbs = new Array(valuesBucket1);
1307try {
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
1326batchInsert(uri: string, values: Array&lt;ValuesBucket&gt;): Promise&lt;number&gt;
1327
1328Batch 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&lt;[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)&gt; | Yes  | Data to insert.      |
1338
1339**Return value**
1340
1341| Type            | Description                                                        |
1342| ---------------- | ------------------------------------------------------------ |
1343| Promise&lt;number&gt; | 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
1348import { ValuesBucket } from '@ohos.data.ValuesBucket'
1349import { BusinessError } from '@ohos.base'
1350
1351let uri = ("datashare:///com.samples.datasharetest.DataShare");
1352let key1: string = "name";
1353let value11: string = "roe11"
1354let key2: string = "age";
1355let value21: number = 21;
1356let key3: string = "salary";
1357let value31: number = 20.5;
1358let valuesBucket1: ValuesBucket = {
1359  key1: value11,
1360  key2: value21,
1361  key3: value31,
1362}
1363let vbs = new Array(valuesBucket1);
1364try {
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
1381normalizeUri(uri: string, callback: AsyncCallback&lt;string&gt;): void
1382
1383Normalizes 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&lt;string&gt; | 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
1397import { BusinessError } from '@ohos.base'
1398
1399let uri = ("datashare:///com.samples.datasharetest.DataShare");
1400if (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
1413normalizeUri(uri: string): Promise&lt;string&gt;
1414
1415Normalizes 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&lt;string&gt; | 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
1434import { BusinessError } from '@ohos.base'
1435
1436let uri = ("datashare:///com.samples.datasharetest.DataShare");
1437if (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
1448denormalizeUri(uri: string, callback: AsyncCallback&lt;string&gt;): void
1449
1450Denormalizes 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&lt;string&gt; | 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
1464import { BusinessError } from '@ohos.base'
1465
1466let uri = ("datashare:///com.samples.datasharetest.DataShare");
1467if (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
1480denormalizeUri(uri: string): Promise&lt;string&gt;
1481
1482Denormalizes 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&lt;string&gt; | 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
1501import { BusinessError } from '@ohos.base'
1502
1503let uri = ("datashare:///com.samples.datasharetest.DataShare");
1504if (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
1515notifyChange(uri: string, callback: AsyncCallback&lt;void&gt;): void
1516
1517Notifies 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&lt;void&gt; | 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
1531let uri = ("datashare:///com.samples.datasharetest.DataShare");
1532if (dataShareHelper != undefined) {
1533  (dataShareHelper as dataShare.DataShareHelper).notifyChange(uri, () => {
1534    console.info("***** notifyChange *****");
1535  });
1536}
1537```
1538
1539### notifyChange
1540
1541notifyChange(uri: string): Promise&lt;void&gt;
1542
1543Notifies 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&lt;void&gt; | Promise that returns no value.|
1558
1559**Example**
1560
1561```ts
1562let uri = ("datashare:///com.samples.datasharetest.DataShare");
1563if (dataShareHelper != undefined) {
1564  (dataShareHelper as dataShare.DataShareHelper).notifyChange(uri);
1565}
1566```
1567