database-datashare-guidelines.md 8.2 KB
Newer Older
A
Annie_wang 已提交
1
# DataShare Development
A
Annie_wang 已提交
2
The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between applications on the same device.
A
Annie_wang 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15

## Available APIs

**Table 1** APIs of the data provider

|API|Description|
|:------|:------|
|onCreate?(want: Want, callback: AsyncCallback<void>): void|Called to initialize service logic when the data provider application is created, for example, when a database is created.|
|insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void|Inserts data into the database.|
|update?(uri: string, predicates: DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void|Updates data in the database.|
|query?(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void|Queries data from the database.|
|delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void|Deletes data from the database.|

A
Annie_wang 已提交
16
For more information, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md).
A
Annie_wang 已提交
17 18 19 20 21 22 23 24 25 26 27

**Table 2** APIs of the data consumer

| API                                                      | Description                              |
| :----------------------------------------------------------- | :--------------------------------- |
| createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void | Creates a **DataShareHelper** instance.             |
| insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void | Inserts a single data record into the database.        |
| update(uri: string, predicates: DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void | Updates data in the database.          |
| query(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void | Queries data from the database.              |
| delete(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void | Deletes one or more data records from the database.|

A
Annie_wang 已提交
28
For more information, see [DataShareHelper](../reference/apis/js-apis-data-dataShare.md).
A
Annie_wang 已提交
29 30 31

## When to Use

A
Annie_wang 已提交
32
There are two roles in **DataShare**:
A
Annie_wang 已提交
33

A
Annie_wang 已提交
34 35
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**.
A
Annie_wang 已提交
36 37 38 39 40 41 42 43

Examples are given below.

### Data Provider Application Development (Only for System Applications)

1. Import the dependencies.

   ```ts
A
Annie_wang 已提交
44
   import Extension from '@ohos.application.DataShareExtensionAbility';
A
Annie_wang 已提交
45
   import rdb from '@ohos.data.rdb';
A
Annie_wang 已提交
46 47
   import fileIo from '@ohos.fileio';
   import dataSharePredicates from '@ohos.data.dataSharePredicates';
A
Annie_wang 已提交
48 49
   ```

A
Annie_wang 已提交
50
2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the **query()** API.
A
Annie_wang 已提交
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82

3. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network.

   ```ts
   let DB_NAME = "DB00.db";
   let TBL_NAME = "TBL00";
   let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
   + TBL_NAME
   + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)";
   
   let rdbStore;
   let result;
   
   export default class DataShareExtAbility extends Extension {
       private rdbStore_;
       
   	// Override the onCreate() API.
       onCreate(want, callback) {
           result = this.context.cacheDir + '/datashare.txt'
           // Create an RDB.
           rdb.getRdbStore(this.context, {
               name: DB_NAME
           }, 1, function (err, data) {
               rdbStore = data;
               rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
                   console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
               });
               callback();
           });
       }
   
   	// Override the query() API.
A
Annie_wang 已提交
83
       query(uri, predicates, columns, callback) {
A
Annie_wang 已提交
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
           if (predicates == null || predicates == undefined) {
               console.info('invalid predicates');
           }
           try {
               rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) {
                   if (resultSet != undefined) {
                       console.info('resultSet.rowCount: ' + resultSet.rowCount);
                   }
                   if (callback != undefined) {
                       callback(err, resultSet);
                   }
               });
           } catch (err) {
               console.error('error' + err);
           }
       }
       // Override other APIs as required.
       // ...
   };
   ```

4. Define **DataShareExtensionAbility** in **module.json5**.

   | Field| Description                                                    |
   | ------------ | ------------------------------------------------------------ |
   | "name"       | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**.        |
A
Annie_wang 已提交
110 111 112
   | "type"       | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template.|
   | "uri"        | URI used for communication. It is the unique identifier for the data consumer to connect to the provider.               |
   | "visible"    | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.|
A
Annie_wang 已提交
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131

   **module.json5 example**

   ```json
   "extensionAbilities": [
     {
       "srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts",
       "name": "DataShareExtAbility",
       "icon": "$media:icon",
       "description": "$string:description_datashareextability",
       "type": "dataShare",
       "uri": "datashare://com.samples.datasharetest.DataShare",
       "visible": true
     }
   ]
   ```

### Data Consumer Application Development

A
Annie_wang 已提交
132
1. Import the dependencies.
A
Annie_wang 已提交
133 134 135 136 137 138 139 140 141 142 143 144 145 146

   ```ts
   import Ability from '@ohos.application.Ability'
   import dataShare from '@ohos.data.dataShare'
   import dataSharePredicates from '@ohos.data.dataSharePredicates'
   ```
   
2. Define the URI string for communicating with the data provider.

   ```ts
   // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/).
   let dseUri = ("datashare:///com.samples.datasharetest.DataShare");
   ```
   
A
Annie_wang 已提交
147
3. Create a **DataShareHelper** instance.
A
Annie_wang 已提交
148 149 150 151

   ```ts
   let dsHelper;
   let abilityContext;
A
Annie_wang 已提交
152
   
A
Annie_wang 已提交
153 154 155
   export default class MainAbility extends Ability {
   	onWindowStageCreate(windowStage) {
   		abilityContext = this.context;
A
Annie_wang 已提交
156
   		dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{
A
Annie_wang 已提交
157 158 159 160 161 162
   			dsHelper = data;
   		});
   	}
   }
   ```
   
A
Annie_wang 已提交
163
4. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data.
A
Annie_wang 已提交
164 165 166

   ```ts
   // Construct a piece of data.
A
Annie_wang 已提交
167 168 169 170
   var valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) };
   var updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
   let da = new dataSharePredicates.DataSharePredicates();
   var valArray = new Array("*");
A
Annie_wang 已提交
171
   let people = new Array(
A
Annie_wang 已提交
172 173 174
     { "name": "LiSi", "age": 41, "Binary": ar },
     { "name": "WangWu", "age": 21, "Binary": arr },
     { "name": "ZhaoLiu", "age": 61, "Binary": arr });
A
Annie_wang 已提交
175
   // Insert a piece of data.
A
Annie_wang 已提交
176 177
   dsHelper.insert(dseUri, valuesBucket, (err, data) => {
     console.log("dsHelper insert result: " + data);
A
Annie_wang 已提交
178
   });
A
Annie_wang 已提交
179
   // Delete data.
A
Annie_wang 已提交
180 181
   dsHelper.delete(dseUri, da, (err, data) => {
     console.log("dsHelper delete result: " + data);
A
Annie_wang 已提交
182 183
   });
   // Update data.
A
Annie_wang 已提交
184 185
   dsHelper.update(dseUri, da, updateBucket, (err, data) => {
     console.log("dsHelper update result: " + data);
A
Annie_wang 已提交
186 187
   });
   // Query data.
A
Annie_wang 已提交
188 189
   dsHelper.query(dseUri, da, valArray, (err, data) => {
     console.log("dsHelper query result: " + data);
A
Annie_wang 已提交
190 191 192
   });
   ```