未验证 提交 fd1b7282 编写于 作者: O openharmony_ci 提交者: Gitee

!14408 [翻译完成】#I69V2G

Merge pull request !14408 from Annie_wang/PR13383
...@@ -34,11 +34,9 @@ There are two roles in **DataShare**: ...@@ -34,11 +34,9 @@ There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**. - Data consumer: accesses the data provided by the provider using **DataShareHelper**.
Examples are given below.
### Data Provider Application Development (Only for System Applications) ### Data Provider Application Development (Only for System Applications)
[DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override the APIs as required. [DataShareExtensionAbility](../reference/apis/js-apis-application-dataShareExtensionAbility.md) provides the following APIs. You can override these APIs as required.
- **onCreate** - **onCreate**
...@@ -82,14 +80,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -82,14 +80,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
```ts ```ts
import Extension from '@ohos.application.DataShareExtensionAbility'; import Extension from '@ohos.application.DataShareExtensionAbility';
import rdb from '@ohos.data.rdb'; import rdb from '@ohos.data.relationalStore';
import fileIo from '@ohos.fileio'; import fileIo from '@ohos.fileio';
import dataSharePredicates from '@ohos.data.dataSharePredicates'; import dataSharePredicates from '@ohos.data.dataSharePredicates';
``` ```
4. Override the **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**. 5. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only **query()**.
5. 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. 6. 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 ```ts
const DB_NAME = "DB00.db"; const DB_NAME = "DB00.db";
...@@ -97,28 +95,31 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -97,28 +95,31 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME + TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)";
let rdbStore; let rdbStore;
let result; let result;
export default class DataShareExtAbility extends Extension { export default class DataShareExtAbility extends Extension {
private rdbStore_; private rdbStore_;
// Override onCreate(). // Override onCreate().
onCreate(want, callback) { onCreate(want, callback) {
result = this.context.cacheDir + '/datashare.txt' result = this.context.cacheDir + '/datashare.txt';
// Create an RDB store. // Create an RDB store.
rdb.getRdbStore(this.context, { rdb.getRdbStore(this.context, {
name: DB_NAME name: DB_NAME,
}, 1, function (err, data) { securityLevel: rdb.SecurityLevel.S1
rdbStore = data; }, function (err, data) {
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { rdbStore = data;
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
}); });
callback(); if (callbakc) {
callback();
}
}); });
} }
// Override query(). // Override query().
query(uri, predicates, columns, callback) { query(uri, predicates, columns, callback) {
if (predicates == null || predicates == undefined) { if (predicates == null || predicates == undefined) {
...@@ -142,17 +143,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -142,17 +143,14 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
}; };
``` ```
7. Define **DataShareExtensionAbility** in **module.json5**.
6. Define **DataShareExtensionAbility** in **module.json5**.
| Field | Description | | Field| Description |
| --------- | ------------------------------------------------------------ | | ------------ | ------------------------------------------------------------ |
| "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. |
| "type" | Ability type. The value is **dataShare**, indicating the development is based on the **datashare** template. | | "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. | | "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**. | | "visible" | Whether it is visible to other applications. Data sharing is allowed only when the value is **true**.|
| | |
**module.json5 example** **module.json5 example**
...@@ -170,8 +168,6 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -170,8 +168,6 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
] ]
``` ```
### Data Consumer Application Development ### Data Consumer Application Development
1. Import dependencies. 1. Import dependencies.
...@@ -212,7 +208,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit ...@@ -212,7 +208,7 @@ Before implementing a **DataShare** service, create a **DataShareExtensionAbilit
let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) }; let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) };
let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) }; let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
let predicates = new dataSharePredicates.DataSharePredicates(); let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = new Array("*"); let valArray = ['*'];
// Insert a piece of data. // Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err, data) => { dsHelper.insert(dseUri, valuesBucket, (err, data) => {
console.log("dsHelper insert result: " + data); console.log("dsHelper insert result: " + data);
......
...@@ -142,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -142,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description | | Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\<Array\<[string, number]>> | Synchronizes data between devices. This API uses a promise to return the result.<br>- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.<br>- **predicates**: specifies the data and devices to synchronize.<br>- **string**: device ID. <br>- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| | RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\<Array\<[string, number]>> | Synchronizes data between devices. This API uses a promise to return the result.<br>- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.<br>- **predicates**: specifies the data and devices to synchronize.<br>- **string**: device ID. <br>- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.|
**Registering an RDB Store Observer** **Registering an RDB Store Observer**
...@@ -180,7 +180,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -180,7 +180,7 @@ You can obtain the distributed table name for a remote device based on the local
### Transaction ### Transaction
Table 15 Transaction APIs **Table 15** Transaction APIs
| Class | API | Description | | Class | API | Description |
| -------- | ----------------------- | --------------------------------- | | -------- | ----------------------- | --------------------------------- |
...@@ -202,44 +202,82 @@ Table 15 Transaction APIs ...@@ -202,44 +202,82 @@ Table 15 Transaction APIs
```js ```js
import data_rdb from '@ohos.data.relationalStore' import data_rdb from '@ohos.data.relationalStore'
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
const STORE_CONFIG = { name: "RdbTest.db", // Assume that the current RDB store version is 3.
securityLevel: data_rdb.SecurityLevel.S1}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST) // When an RDB store is created, the default version is 0.
console.info('create table done.') if (rdbStore.version == 0) {
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null)
// Set the RDB store version. The input parameter must be an integer greater than 0.
rdbStore.version = 3
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null)
rdbStore.version = 2
}
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null)
rdbStore.version = 3
}
}) })
``` ```
Stage model: Stage model:
```ts ```ts
import data_rdb from '@ohos.data.relationalStore' import data_rdb from '@ohos.data.relationalStore'
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context = null
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
context = this.context const STORE_CONFIG = {
name: "rdbstore.db",
securityLevel: data_rdb.SecurityLevel.S1
}
// Assume that the current RDB store version is 3.
data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) {
// When an RDB store is created, the default version is 0.
if (rdbStore.version == 0) {
rdbStore.executeSql("CREATE TABLE IF NOT EXISTS student (id INTEGER PRIMARY KEY AUTOINCREMENT, score REAL);", null)
// Set the RDB store version. The input parameter must be an integer greater than 0.
rdbStore.version = 3
}
// When an app is updated to the current version, the RDB store needs to be updated from version 1 to version 2.
if (rdbStore.version != 3 && rdbStore.version == 1) {
// version = 1: table structure: student (id, age) => version = 2: table structure: student (id, age, score)
rdbStore.executeSql("ALTER TABLE student ADD COLUMN score REAL", null)
rdbStore.version = 2
}
// When an app is updated to the current version, the RDB store needs to be updated from version 2 to version 3.
if (rdbStore.version != 3 && rdbStore.version == 2) {
// version = 2: table structure: student (id, age, score) => version = 3: table structure: student (id, score)
rdbStore.executeSql("ALTER TABLE student DROP COLUMN age INTEGER", null)
rdbStore.version = 3
}
})
} }
} }
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = { name: "rdbstore.db",
securityLevel: data_rdb.SecurityLevel.S1}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
``` ```
2. Insert data. 2. Insert data.
(1) Create a **ValuesBucket** to store the data you need to insert. (1) Create a **ValuesBucket** instance to store the data you need to insert.
(2) Call the **insert()** method to insert data into the RDB store. (2) Call the **insert()** method to insert data into the RDB store.
...@@ -384,14 +422,13 @@ Table 15 Transaction APIs ...@@ -384,14 +422,13 @@ Table 15 Transaction APIs
8. Query data of a remote device. 8. Query data of a remote device.
(1) Construct a predicate object for querying distributed tables, and specify the remote distributed table name and the remote device. (1) Construct a predicate object for querying distributed tables, and specify the remote distributed table name and the remote device.
(2) Call the resultSet() API to obtain the result. (2) Call the resultSet() API to obtain the result.
The sample code is as follows: The sample code is as follows:
```js ```js
let rdbPredicate = new data_rdb.RdbPredicates('employee') let rdbPredicate = new data_rdb.RdbPredicates('employee')
predicates.greaterThan("id", 0) predicates.greaterThan("id", 0)
let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate)
...@@ -406,31 +443,32 @@ Table 15 Transaction APIs ...@@ -406,31 +443,32 @@ Table 15 Transaction APIs
}).catch((err) => { }).catch((err) => {
console.info("failed to remoteQuery, err: " + err) console.info("failed to remoteQuery, err: " + err)
}) })
``` ```
9. Back up and restore an RDB store. 9. Back up and restore an RDB store.
(1) Back up the current RDB store. (1) Back up the current RDB store.
The sample code is as follows: The sample code is as follows:
```js ```js
let promiseBackup = rdbStore.backup("dbBackup.db") let promiseBackup = rdbStore.backup("dbBackup.db")
promiseBackup.then(() => { promiseBackup.then(() => {
console.info('Backup success.') console.info('Backup success.')
}).catch((err) => { }).catch((err) => {
console.info('Backup failed, err: ' + err) console.info('Backup failed, err: ' + err)
}) })
``` ```
(2) Restore the RDB store using the backup file.
The sample code is as follows: (2) Restore the RDB store using the backup file.
```js The sample code is as follows:
```js
let promiseRestore = rdbStore.restore("dbBackup.db") let promiseRestore = rdbStore.restore("dbBackup.db")
promiseRestore.then(() => { promiseRestore.then(() => {
console.info('Restore success.') console.info('Restore success.')
}).catch((err) => { }).catch((err) => {
console.info('Restore failed, err: ' + err) console.info('Restore failed, err: ' + err)
}) })
``` ```
...@@ -33,7 +33,7 @@ ArkTS sample code: ...@@ -33,7 +33,7 @@ ArkTS sample code:
globalThis.context.startAbilityForResult( globalThis.context.startAbilityForResult(
{ {
bundleName: "com.ohos.filepicker", bundleName: "com.ohos.filepicker",
abilityName: "EntryAbility", abilityName: "MainAbility",
parameters: { parameters: {
'startMode': 'choose', //choose or save 'startMode': 'choose', //choose or save
} }
...@@ -45,7 +45,7 @@ globalThis.context.startAbilityForResult( ...@@ -45,7 +45,7 @@ globalThis.context.startAbilityForResult(
globalThis.context.startAbilityForResult( globalThis.context.startAbilityForResult(
{ {
bundleName: "com.ohos.filepicker", bundleName: "com.ohos.filepicker",
abilityName: "EntryAbility", abilityName: "MainAbility",
parameters: { parameters: {
'startMode': 'save', //choose or save 'startMode': 'save', //choose or save
'saveFile': 'test.jpg', 'saveFile': 'test.jpg',
......
...@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re ...@@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.| | name | string | Yes | Name of the **Preferences** instance.|
| callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;[Preferences](#preferences)&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.|
...@@ -69,9 +69,11 @@ Stage model: ...@@ -69,9 +69,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -103,7 +105,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result ...@@ -103,7 +105,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance.| | name | string | Yes | Name of the **Preferences** instance.|
**Return value** **Return value**
...@@ -139,9 +141,11 @@ Stage model: ...@@ -139,9 +141,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -177,7 +181,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -177,7 +181,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete. | | name | string | Yes | Name of the **Preferences** instance to delete. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
...@@ -215,9 +219,11 @@ Stage model: ...@@ -215,9 +219,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -252,7 +258,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi ...@@ -252,7 +258,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to delete.| | name | string | Yes | Name of the **Preferences** instance to delete.|
**Return value** **Return value**
...@@ -294,9 +300,11 @@ Stage model: ...@@ -294,9 +300,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -328,7 +336,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -328,7 +336,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove. | | name | string | Yes | Name of the **Preferences** instance to remove. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.|
...@@ -358,9 +366,11 @@ Stage model: ...@@ -358,9 +366,11 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{
class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
...@@ -394,7 +404,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi ...@@ -394,7 +404,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------- | ------------------------------------- | ---- | ----------------------- | | ------- | ------------------------------------- | ---- | ----------------------- |
| context | Context | Yes | Application context.<br>For the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md). | | context | Context | Yes | Application context.<br>For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).<br>For details about the application context of the stage model, see [Context](js-apis-ability-context.md). |
| name | string | Yes | Name of the **Preferences** instance to remove.| | name | string | Yes | Name of the **Preferences** instance to remove.|
**Return value** **Return value**
...@@ -428,9 +438,9 @@ Stage model: ...@@ -428,9 +438,9 @@ Stage model:
```ts ```ts
// Obtain the context. // Obtain the context.
import Ability from '@ohos.application.Ability'; import UIAbility from '@ohos.app.ability.UIAbility';
let context = null; let context = null;
class MainAbility extends Ability{ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context; context = this.context;
} }
......
...@@ -48,26 +48,21 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -48,26 +48,21 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = { const STORE_CONFIG = {
name: "RdbTest.db", name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1 securityLevel: data_rdb.SecurityLevel.S1
} }
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
if (err) { if (err) {
console.info("Failed to get RdbStore, err: " + err) console.info("Failed to get RdbStore, err: " + err)
return return
}
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
} }
console.log("Got RdbStore successfully.") console.log("Got RdbStore successfully.")
}) })
...@@ -76,36 +71,24 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) { ...@@ -76,36 +71,24 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
data_rdb.getRdbStore(this.context, STORE_CONFIG, function (err, rdbStore) {
if (err) {
console.info("Failed to get RdbStore, err: " + err)
return
}
console.log("Got RdbStore successfully.")
})
} }
} }
// Call getRdbStore.
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
if (err) {
console.info("Failed to get RdbStore, err: " + err)
return
}
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.")
})
``` ```
## data_rdb.getRdbStore ## data_rdb.getRdbStore
...@@ -143,24 +126,18 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -143,24 +126,18 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call getRdbStore.
const STORE_CONFIG = { const STORE_CONFIG = {
name: "RdbTest.db", name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1 securityLevel: data_rdb.SecurityLevel.S1
} }
let promise = data_rdb.getRdbStore(context, STORE_CONFIG); let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => { promise.then(async (rdbStore) => {
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.") console.log("Got RdbStore successfully.")
}).catch((err) => { }).catch((err) => {
console.log("Failed to get RdbStore, err: " + err) console.log("Failed to get RdbStore, err: " + err)
...@@ -170,35 +147,23 @@ promise.then(async (rdbStore) => { ...@@ -170,35 +147,23 @@ promise.then(async (rdbStore) => {
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG);
promise.then(async (rdbStore) => {
console.log("Got RdbStore successfully.")
}).catch((err) => {
console.log("Failed to get RdbStore, err: " + err)
})
} }
} }
// Call getRdbStore.
const STORE_CONFIG = {
name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1
}
let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => {
if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
return
}
console.log("Got RdbStore successfully.")
}).catch((err) => {
console.log("Failed to get RdbStore, err: " + err)
})
``` ```
## data_rdb.deleteRdbStore ## data_rdb.deleteRdbStore
...@@ -230,11 +195,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -230,11 +195,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) { if (err) {
console.info("Failed to delete RdbStore, err: " + err) console.info("Failed to delete RdbStore, err: " + err)
...@@ -247,25 +212,19 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { ...@@ -247,25 +212,19 @@ data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
return
}
console.log("Deleted RdbStore successfully.")
})
} }
} }
// Call deleteRdbStore.
data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) {
if (err) {
console.info("Failed to delete RdbStore, err: " + err)
return
}
console.log("Deleted RdbStore successfully.")
})
``` ```
## data_rdb.deleteRdbStore ## data_rdb.deleteRdbStore
...@@ -302,11 +261,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode ...@@ -302,11 +261,11 @@ For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode
FA model: FA model:
```js ```js
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
// Obtain the context.
let context = featureAbility.getContext() let context = featureAbility.getContext()
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{ promise.then(()=>{
console.log("Deleted RdbStore successfully.") console.log("Deleted RdbStore successfully.")
...@@ -318,24 +277,18 @@ promise.then(()=>{ ...@@ -318,24 +277,18 @@ promise.then(()=>{
Stage model: Stage model:
```ts ```ts
// Obtain the context. import UIAbility from '@ohos.app.ability.UIAbility'
import UIAbility from '@ohos.app.ability.UIAbility';
let context;
class EntryAbility extends UIAbility { class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage){ onWindowStageCreate(windowStage){
context = this.context let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
}).catch((err) => {
console.info("Failed to delete RdbStore, err: " + err)
})
} }
} }
// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(context, "RdbTest.db")
promise.then(()=>{
console.log("Deleted RdbStore successfully.")
}).catch((err) => {
console.info("Failed to delete RdbStore, err: " + err)
})
``` ```
## StoreConfig ## StoreConfig
...@@ -423,17 +376,6 @@ Defines the resolution to use when **insert()** and **update()** conflict. ...@@ -423,17 +376,6 @@ Defines the resolution to use when **insert()** and **update()** conflict.
| ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.| | ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.|
| ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.| | ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.|
## OpenStatus<sup>10+</sup>
Enumerates the RDB store status.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
| Name | Value | Description |
| --------- | ---- | --------------------------------------------------- |
| ON_CREATE | 0 | The RDB store is created for the first time. |
| ON_OPEN | 1 | The RDB store is already created. |
## RdbPredicates ## RdbPredicates
Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false.
...@@ -1283,7 +1225,16 @@ Before using the following APIs, use [executeSql](#executesql) to initialize the ...@@ -1283,7 +1225,16 @@ Before using the following APIs, use [executeSql](#executesql) to initialize the
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------------ | ----------- | ---- | -------------------------------- | | ------------ | ----------- | ---- | -------------------------------- |
| openStatus<sup>10+</sup> | number | Yes | RDB store status. The value **0** indicates the **ON_CREATE** state, which means the RDB store is created for the first time. The value **1** indicates the **ON_OPEN** state, which means the RDB store is already created. | | version<sup>10+</sup> | number | Yes | RDB store version, which is an integer greater than 0. |
**Example**
```js
// Set the RDB store version.
rdbStore.version = 3
// Obtain the RDB store version.
console.info("Get RdbStore version is " + rdbStore.version)
```
### insert ### insert
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册