diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 13110f9784e44ab0d406917924394ef5b84fc470..35e00ce945cb1a355f451d4962b351e2fa8e040b 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -202,7 +202,7 @@ - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md) - [@ohos.data.preferences](js-apis-data-preferences.md) - - [@ohos.data.rdb](js-apis-data-rdb.md) + - [@ohos.data.relationalStore](js-apis-data-relationalStore.md) - [@ohos.data.ValuesBucket](js-apis-data-valuesBucket.md) - data/rdb - [resultSet](js-apis-data-resultset.md) @@ -339,6 +339,7 @@ - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@ohos.bytrace](js-apis-bytrace.md) - [@ohos.data.storage](js-apis-data-storage.md) + - [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.distributedData](js-apis-distributed-data.md) - [@ohos.distributedBundle](js-apis-Bundle-distributedBundle.md) - [@ohos.document](js-apis-document.md) diff --git a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md index c6192ce1235b2c75607e92788b68fd635dddaffd..9ecffc326e125b6e7dbe0ecd3cf03bfc3d2fa7dd 100644 --- a/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md @@ -1,6 +1,6 @@ # @ohos.application.DataShareExtensionAbility -The **DataShareExtensionAbility** module provides extension abilities for data share services. +The **DataShareExtensionAbility** module provides data share services based on the Extension ability. >**NOTE** > @@ -17,13 +17,34 @@ The **DataShareExtensionAbility** module provides extension abilities for data s import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility' ``` +## URI Naming Rule + +The URIs are in the following format: + +**Scheme://authority/path** + +- *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module. +- *authority*: [userinfo@]host[:port] + - *userinfo*: login information, which can be left unspecified. + - *host*: server address. It is the target device ID for cross-device access and empty for local device access. + - *port*: port number of the server, which can be left unspecified. +- *path*: **DataShare** identifier and the resource path. The **DataShare** identifier is mandatory, and the resource path is optional. + +Example: + +- URI without the resource path:
**datashare:///com.samples.datasharetest.DataShare** + +- URI with the resource path:
**datashare:///com.samples.datasharetest.DataShare/DB00/TBL00** + +**com.samples.datasharetest.DataShare** is the data share identifier, and **DB00/TBL00** is the resource path. + ## Attributes **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|Context of the DataShare Extension ability.| +| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|Context of the DataShare Extension ability.| ## onCreate @@ -43,7 +64,7 @@ Called by the server to initialize service logic when the DataShare client conne **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -56,7 +77,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { onCreate(want, callback) { rdb.getRdbStore(this.context, { name: DB_NAME - }, 1, function (err, data) { + }, function (err, data) { console.log('getRdbStore done, data : ' + data); rdbStore = data; rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { @@ -89,7 +110,7 @@ Inserts data into the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -134,7 +155,7 @@ Updates data in the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -176,7 +197,7 @@ Deletes data from the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -219,7 +240,7 @@ Queries data from the database. This API can be overridden as required. **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -264,7 +285,7 @@ Batch inserts data into the database. This API is called by the server and can b **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index 5fedece20aac3dc30e68020964be1fbca1cefdfa..ccc1f7b4e26c0cbc6556f2ea767c5601ac3a477e 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -1,4 +1,4 @@ -# Data Share Result Set +# @ohos.data.dataShareResultSet The **DataShareResultSet** module provides APIs for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md index a5f16c8c04d650608231c4757224c662c23bf387..2a476aaf33cc927b8c0ec5c392a083b6b42c8f80 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -1,4 +1,4 @@ -# Data Sharing +# @ohos.data.dataShare The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. @@ -17,6 +17,26 @@ The **DataShare** module allows an application to manage its own data and share import dataShare from '@ohos.data.dataShare' ``` +## URI Naming Rule + +The URIs are in the following format: + +**Scheme://authority/path** +- *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module. +- *authority*: [userinfo@]host[:port] + - *userinfo*: login information, which can be left unspecified. + - *host*: server address. It is the target device ID for cross-device access and empty for local device access. + - *port*: port number of the server, which can be left unspecified. +- *path*: **DataShare** identifier and the resource path. The **DataShare** identifier is mandatory, and the resource path is optional. + +Example: + +- URI without the resource path:
**datashare:///com.samples.datasharetest.DataShare** + +- URI with the resource path:
**datashare:///com.samples.datasharetest.DataShare/DB00/TBL00** + +**com.samples.datasharetest.DataShare** is the data share identifier, and **DB00/TBL00** is the resource path. + ## dataShare.createDataShareHelper @@ -24,6 +44,11 @@ createDataShareHelper(context: Context, uri: string, callback: AsyncCallback< Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - 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. + - If **visible** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - 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). + **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -34,21 +59,33 @@ Creates a **DataShareHelper** instance. This API uses an asynchronous callback t | uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect. | | 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.| +**Error codes** + +For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). + +| ID| Error Message | +| -------- | ---------------------------------------------------- | +| 15700010 | The dataShareHelper is not initialized successfully. | + **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let dataShareHelper; -dataShare.createDataShareHelper(this.context, uri, (err, data) => { - if (err != undefined) { - console.info("createDataShareHelper failed, error message : " + err); - } else { +try { + dataShare.createDataShareHelper(this.context, uri, (err, data) => { + if (err != undefined) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); + return; + } console.info("createDataShareHelper succeed, data : " + data); dataShareHelper = data; - } -}); + }); +} catch (err) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); +}; ``` ## dataShare.createDataShareHelper @@ -57,6 +94,11 @@ createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper Creates a **DataShareHelper** instance. This API uses a promise to return the result. +Observe the following when using this API: + - 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. + - If **visible** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - 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). + **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -72,19 +114,31 @@ Creates a **DataShareHelper** instance. This API uses a promise to return the re | -------------------------------------------------- | -------------------------------------- | | Promise<[DataShareHelper](#datasharehelper)> | Promise used to return the **DataShareHelper** instance created.| +**Error codes** + +For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). + +| ID| Error Message | +| -------- | ---------------------------------------------------- | +| 15700010 | The dataShareHelper is not initialized successfully. | + **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let dataShareHelper; -dataShare.createDataShareHelper(this.context, uri).then((data) => { - console.info("createDataShareHelper succeed, data : " + data); - dataShareHelper = data; -}).catch((err) => { - console.info("createDataShareHelper failed, error message : " + err); -}) +try { + dataShare.createDataShareHelper(this.context, uri).then((data) => { + console.info("createDataShareHelper succeed, data : " + data); + dataShareHelper = data; + }). catch((err) => { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); +}; ``` ## DataShareHelper @@ -101,16 +155,17 @@ Subscribes to changes of the specified data. After an observer is registered, th **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | type | string | Yes | Event type to subscribe to. The value is **dataChange**, which indicates data change events.| | uri | string | Yes | URI of the data.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the data is changed, the value of **err** is **undefined**. Otherwise, this callback is not invoked or the value of **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If data is changed, the value of **err** is undefined. Otherwise, this callback is not invoked or the value of **err** is an error object.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + function onCallback() { console.info("**** Observer on callback ****"); } @@ -128,7 +183,7 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.| | uri | string | Yes | URI of the data.| @@ -137,7 +192,8 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + function offCallback() { console.info("**** Observer off callback ****"); } @@ -155,29 +211,34 @@ Inserts a single data record into the database. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to insert. | -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted. | +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the index of the inserted data record. Otherwise, **err** is an error object.
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.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose", "age": 22, "salary": 200.5, } -dataShareHelper.insert(uri, valueBucket, (err, data) => { - if (err != undefined) { - console.log("insert failed, error message : " + err); - }else{ - console.log("insert succeed, data : " + data); - } -}); +try { + dataShareHelper.insert(uri, valueBucket, (err, data) => { + if (err != undefined) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); + return; + } + console.info("insert succeed, data : " + data); + }); +} catch (err) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### insert @@ -193,7 +254,7 @@ Inserts a single data record into the database. This API uses a promise to retur | Name | Type | Mandatory| Description | | ----- | --------------------------------------------------------- | ---- | -------------------------------------------------- | | uri | string | Yes | URI of the data to insert. | -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted.| **Return value** @@ -204,18 +265,23 @@ Inserts a single data record into the database. This API uses a promise to retur **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose1", "age": 221, "salary": 20.5, } -dataShareHelper.insert(uri, valueBucket).then((data) => { - console.log("insert succeed, data : " + data); -}).catch((err) => { - console.log("insert failed, error message : " + err); -}); +try { + dataShareHelper.insert(uri, valueBucket).then((data) => { + console.log("insert succeed, data : " + data); + }). catch((err) => { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### delete @@ -231,25 +297,29 @@ Deletes one or more data records from the database. This API uses an asynchronou | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of deleted data records. Otherwise, **err** is an error object.
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.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.delete(uri, da, (err, data) => { - if (err != undefined) { - console.log("delete failed, error message : " + err); - }else{ - console.log("delete succeed, data : " + data); - } -}); +try { + dataShareHelper.delete(uri, da, (err, data) => { + if (err != undefined) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); + return; + } + console.info("delete succeed, data : " + data); + }); +} catch (err) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); +}; ``` ### delete @@ -265,7 +335,7 @@ Deletes one or more data records from the database. This API uses a promise to r | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| **Return value** @@ -276,17 +346,21 @@ Deletes one or more data records from the database. This API uses a promise to r **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.delete(uri, da).then((data) => { - console.log("delete succeed, data : " + data); -}).catch((err) => { - console.log("delete failed, error message : " + err); -}); +try { + dataShareHelper.delete(uri, da).then((data) => { + console.log("delete succeed, data : " + data); + }). catch((err) => { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); +}; ``` ### query @@ -302,27 +376,31 @@ Queries data in the database. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| | columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | | callback | AsyncCallback<[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the result set obtained. Otherwise, **err** is an error object.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.query(uri, da, columns, (err, data) => { - if (err != undefined) { - console.log("query failed, error message : " + err); - }else{ +try { + dataShareHelper.query(uri, da, columns, (err, data) => { + if (err != undefined) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("query succeed, rowCount : " + data.rowCount); - } -}); + }); +} catch (err) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); +}; ``` ### query @@ -338,7 +416,7 @@ Queries data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| | columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | **Return value** @@ -350,18 +428,22 @@ Queries data in the database. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.query(uri, da, columns).then((data) => { - console.log("query succeed, rowCount : " + data.rowCount); -}).catch((err) => { - console.log("query failed, error message : " + err); -}); +try { + dataShareHelper.query(uri, da, columns).then((data) => { + console.log("query succeed, rowCount : " + data.rowCount); + }). catch((err) => { + console.error(`query error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); +}; ``` ### update @@ -377,15 +459,15 @@ Updates data in the database. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | New data. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of updated data records. Otherwise, **err** is an error object.
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.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); @@ -396,13 +478,17 @@ const va = { "salary": 20.5, } -dataShareHelper.update(uri, da, va, (err, data) => { - if (err != undefined) { - console.log("update failed, error message : " + err); - }else{ +try { + dataShareHelper.update(uri, da, va, (err, data) => { + if (err != undefined) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("update succeed, data : " + data); - } -}); + }); +} catch (err) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); +}; ``` ### update @@ -418,8 +504,8 @@ Updates data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | New data. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data. | **Return value** @@ -430,8 +516,8 @@ Updates data in the database. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); @@ -442,11 +528,15 @@ const va = { "salary": 20.5, } -dataShareHelper.update(uri, da, va).then((data) => { - console.log("update succeed, data : " + data); -}).catch((err) => { - console.log("update failed, error message : " + err); -}); +try { + dataShareHelper.update(uri, da, va).then((data) => { + console.log("update succeed, data : " + data); + }). catch((err) => { + console.error(`update error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); +}; ``` ### batchInsert @@ -462,24 +552,29 @@ Batch inserts data into the database. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to insert. | -| values | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | +| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of data records inserted. Otherwise, **err** is an error object.
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.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, {"name": "roe13", "age": 21, "salary": 20.5,}) -dataShareHelper.batchInsert(uri, vbs, (err, data) => { - if (err != undefined) { - console.log("batchInsert failed, error message : " + err); - }else{ +try { + dataShareHelper.batchInsert(uri, vbs, (err, data) => { + if (err != undefined) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("batchInsert succeed, data : " + data); - } -}); + }); +} catch (err) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### batchInsert @@ -495,7 +590,7 @@ Batch inserts data into the database. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | | uri | string | Yes | URI of the data to insert.| -| values | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | +| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | **Return value** @@ -506,16 +601,21 @@ Batch inserts data into the database. This API uses a promise to return the resu **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, {"name": "roe13", "age": 21, "salary": 20.5,}) -dataShareHelper.batchInsert(uri, vbs).then((data) => { - console.log("batchInsert succeed, data : " + data); -}).catch((err) => { - console.log("batchInsert failed, error message : " + err); -}); +try { + dataShareHelper.batchInsert(uri, vbs).then((data) => { + console.log("batchInsert succeed, data : " + data); + }). catch((err) => { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### normalizeUri @@ -536,7 +636,8 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri, (err, data) => { if (err != undefined) { @@ -570,7 +671,8 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri).then((data) => { console.log("normalizeUri = " + data); @@ -597,7 +699,8 @@ Denormalizes a URI. This API uses an asynchronous callback to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri, (err, data) => { if (err != undefined) { @@ -631,7 +734,8 @@ Denormalizes a URI. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri).then((data) => { console.log("denormalizeUri = " + data); @@ -650,7 +754,7 @@ Notifies the registered observer of data changes. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | uri | string | Yes | URI of the data.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the observer is notified of the data changes, **err** is **undefined**. Otherwise, **err** is an error object.| @@ -658,7 +762,8 @@ Notifies the registered observer of data changes. This API uses an asynchronous **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri, () => { console.log("***** notifyChange *****"); @@ -688,7 +793,8 @@ Notifies the registered observer of data changes. This API uses a promise to ret **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri); ``` diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 87c75a024fb144c72c0942e44b114a7d250a8008..89ebac58ef1f970c8c97c00bedb0fe5552491115 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -1,4 +1,4 @@ -# Relational Database +# @ohos.data.rdb The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. @@ -8,15 +8,17 @@ This module provides the following RDB-related functions: - [RdbStore](#rdbstore): provides APIs for managing an RDB store. > **NOTE**
-> +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are no longer maintained since API version 9. You are advised to use [@ohos.data.relationalStore](js-apis-data-relationalStore.md). + ## Modules to Import ```js import data_rdb from '@ohos.data.rdb'; ``` - ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void @@ -27,12 +29,12 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| -| version | number | Yes| RDB store version.| -| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes| Callback invoked to return the RDB store obtained.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| version | number | Yes | RDB store version.
Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported. | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes | Callback invoked to return the RDB store obtained. | **Example** @@ -41,7 +43,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db"} @@ -58,9 +60,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -76,6 +79,7 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { console.log("Got RdbStore successfully.") }) ``` + ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> @@ -86,16 +90,16 @@ Obtains an RDB store. This API uses a promise to return the result. You can set **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes|Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| -| version | number | Yes| RDB store version.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| version | number | Yes | RDB store version.
Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------------------------ | ------------------------------- | | Promise<[RdbStore](#rdbstore)> | Promise used to return the RDB store obtained.| **Example** @@ -105,7 +109,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db" } @@ -121,9 +125,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -149,11 +154,11 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| name | string | Yes| Name of the RDB store to delete.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** @@ -162,7 +167,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call deleteRdbStore. data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { @@ -178,9 +183,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -206,16 +212,16 @@ Deletes an RDB store. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| name | string | Yes| Name of the RDB store to delete.| +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -224,11 +230,11 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call deleteRdbStore. let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") -promise.then(()=>{ +promise.then(() => { console.log("Deleted RdbStore successfully.") }).catch((err) => { console.info("Failed to delete RdbStore, err: " + err) @@ -239,9 +245,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -256,16 +263,70 @@ promise.then(()=>{ }) ``` +## ValueType + +Defines the data types allowed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Type | Description | +| ------- | -------------------- | +| number | Number. | +| string | String. | +| boolean | Boolean.| + + +## ValuesBucket + +Defines the types of the key and value in a KV pair. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Key Type| Value Type | +| ------ | ----------------------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | + +## SyncMode8+ + +Defines the database synchronization mode. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| -------------- | ---- | ---------------------------------- | +| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| +| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device. | + +## SubscribeType8+ + +Defines the subscription type. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------------ | +| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| + +## StoreConfig + +Defines the RDB store configuration. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Database file name.| + ## RdbPredicates Defines predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. - ### constructor constructor(name: string) - A constructor used to create an **RdbPredicates** object. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -286,8 +347,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") inDevices(devices: Array<string>): RdbPredicates - -Sets an **RdbPredicates** to specify the remote devices on the network to connect during distributed database synchronization. +Sets an **RdbPredicates** to specify the remote devices to connect on the network during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -314,7 +374,6 @@ predicates.inDevices(['12345678abcde']) inAllDevices(): RdbPredicates - Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -336,7 +395,6 @@ predicates.inAllDevices() equalTo(field: string, value: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -366,7 +424,6 @@ predicates.equalTo("NAME", "lisi") notEqualTo(field: string, value: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -396,7 +453,6 @@ predicates.notEqualTo("NAME", "lisi") beginWrap(): RdbPredicates - Adds a left parenthesis to the **RdbPredicates**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1098,7 +1154,7 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) Provides methods to manage an RDB store. -Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). +Before using the following APIs, use [executeSql](#executesql8) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). ### insert @@ -1172,7 +1228,7 @@ promise.then((rowId) => { }) ``` -### batchInsert9+ +### batchInsert batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void @@ -1210,7 +1266,7 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { if (status) { console.log("Failed to batch insert data, status = " + status); @@ -1220,7 +1276,7 @@ rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { }) ``` -### batchInsert9+ +### batchInsert batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> @@ -1263,7 +1319,7 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); promise.then((insertNum) => { console.log("Batch inserted data successfully. The number of values that were inserted = " + insertNum); @@ -1299,12 +1355,12 @@ const valueBucket = { } let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") -rdbStore.update(valueBucket, predicates, function (err, ret) { +rdbStore.update(valueBucket, predicates, function (err, rows) { if (err) { console.info("Failed to update data, err: " + err) return } - console.log("Updated row count: " + ret) + console.log("Updated row count: " + rows) }) ``` @@ -1341,91 +1397,8 @@ const valueBucket = { let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") let promise = rdbStore.update(valueBucket, predicates) -promise.then(async (ret) => { - console.log("Updated row count: " + ret) -}).catch((err) => { - console.info("Failed to update data, err: " + err) -}) -``` - -### update9+ -update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void - -Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { - if (err) { - console.info("Failed to update data, err: " + err) - return - } - console.log("Updated row count: " + ret) -}) -``` - -### update9+ - -update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> - -Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) -promise.then(async (ret) => { - console.log("Updated row count: " + ret) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) }).catch((err) => { console.info("Failed to update data, err: " + err) }) @@ -1493,76 +1466,6 @@ promise.then((rows) => { }) ``` -### delete9+ - -delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void - -Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { - if (err) { - console.info("Failed to delete data, err: " + err) - return - } - console.log("Deleted rows: " + rows) -}) -``` - -### delete9+ - -delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise<number> - -Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete("EMPLOYEE", predicates) -promise.then((rows) => { - console.log("Deleted rows: " + rows) -}).catch((err) => { - console.info("Failed to delete data, err: " + err) -}) -``` - ### query query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void @@ -1629,151 +1532,6 @@ Queries data from the RDB store based on specified conditions. This API uses a p }) ``` -### query9+ - -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void - -Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| -| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { - if (err) { - console.info("Failed to query data, err: " + err) - return - } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) -}) -``` - -### query9+ - -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> - -Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| -| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) -}).catch((err) => { - console.info("Failed to query data, err: " + err) -}) -``` - -### remoteQuery9+ - -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void - -Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| device | string | Yes| Network ID of the remote device.| -| table | string | Yes| Name of the target table.| -| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| -| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md#resultset)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], - function(err, resultSet){ - if (err) { - console.info("Failed to remoteQuery, err: " + err) - return - } - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}) -``` - -### remoteQuery9+ - -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> - -Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| device | string | Yes| Network ID of the remote device.| -| table | string | Yes| Name of the target table.| -| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| -| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | -------------------------------------------------------- | -| Promise<[ResultSet](js-apis-data-resultset.md#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSet) => { - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}).catch((err) => { - console.info("Failed to remoteQuery , err: " + err) -}) -``` - ### querySql8+ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void @@ -1836,7 +1594,7 @@ promise.then((resultSet) => { }) ``` -### executeSql +### executeSql8+ executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void @@ -1865,7 +1623,7 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { }) ``` -### executeSql +### executeSql8+ executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> @@ -1884,7 +1642,7 @@ Executes an SQL statement that contains specified arguments but returns no value | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -1910,7 +1668,7 @@ Starts the transaction before executing an SQL statement. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1937,7 +1695,7 @@ Commits the executed SQL statements. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1964,7 +1722,7 @@ Rolls back the SQL statements that have been executed. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { try { @@ -1984,122 +1742,6 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### backup9+ - -backup(destName:string, callback: AsyncCallback<void>):void - -Backs up an RDB store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| destName | string | Yes| Name of the RDB store backup file.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| - -**Example** - -```js -rdbStore.backup("dbBackup.db", function(err) { - if (err) { - console.info('Failed to back up data, err: ' + err) - return - } - console.info('Backed up data successfully.') -}) -``` - -### backup9+ - -backup(destName:string): Promise<void> - -Backs up an RDB store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| destName | string | Yes| Name of the RDB store backup file.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -```js -let promiseBackup = rdbStore.backup("dbBackup.db") -promiseBackup.then(()=>{ - console.info('Backed up data successfully.') -}).catch((err)=>{ - console.info('Failed to back up data, err: ' + err) -}) -``` - -### restore9+ - -restore(srcName:string, callback: AsyncCallback<void>):void - -Restores an RDB store from a backup file. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| srcName | string | Yes| Name of the RDB store backup file.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| - -**Example** - -```js -rdbStore.restore("dbBackup.db", function(err) { - if (err) { - console.info('Failed to restore data, err: ' + err) - return - } - console.info('Restored data successfully.') -}) -``` - -### restore9+ - -restore(srcName:string): Promise<void> - -Restores an RDB store from a backup file. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| srcName | string | Yes| Name of the RDB store backup file.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -```js -let promiseRestore = rdbStore.restore("dbBackup.db") -promiseRestore.then(()=>{ - console.info('Restored data successfully.') -}).catch((err)=>{ - console.info('Failed to restore data, err: ' + err) -}) -``` - ### setDistributedTables8+ setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void @@ -2149,7 +1791,7 @@ Sets distributed tables. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -2306,8 +1948,6 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<stri Registers an observer for this RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -2315,7 +1955,7 @@ Registers an observer for this RDB store. When the data in the RDB store changes | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | string | Yes| The value is'dataChange', which indicates a data change event.| -| type | [SubscribeType](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| type | [SubscribeType](#subscribetype8) | Yes| Subscription type to register.| | observer | Callback<Array<string>> | Yes| Observer that listens for the data changes in the RDB store.| **Example** @@ -2339,8 +1979,6 @@ off(event:'dataChange', type: SubscribeType, observer: Callback<Array<stri Unregisters the observer of the specified type from the RDB store. This API uses a callback to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -2348,7 +1986,7 @@ Unregisters the observer of the specified type from the RDB store. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | string | Yes| The value is'dataChange', which indicates a data change event.| -| type | [SubscribeType](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| type | [SubscribeType](#subscribetype8) | Yes| Subscription type to unregister.| | observer | Callback<Array<string>> | Yes| Data change observer registered.| **Example** @@ -2365,60 +2003,3 @@ try { console.log('Failed to unregister observer') } ``` - -## StoreConfig - -Defines the RDB store configuration. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Database file name.| -| encrypt9+ | boolean | No| Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store, and the value **false** means the opposite.| - -## ValueType - -Defines the data types allowed. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Type| Description| -| -------- | -------- | -| number | Number.| -| string | String.| -| boolean | Boolean.| - - -## ValuesBucket - -Defines the types of the key and value in a KV pair. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Key Type| Value Type| -| -------- | -------- | -| string | [ValueType](#valuetype)\| Uint8Array \| null | - -## SyncMode8+ - -Defines the database synchronization mode. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Default Value| Description| -| -------- | ----- |----- | -| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| -| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device.| - -## SubscribeType8+ - -Defines the subscription type. - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Default Value| Description| -| -------- | ----- |---- | -| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| diff --git a/en/application-dev/reference/apis/js-apis-data-relationalStore.md b/en/application-dev/reference/apis/js-apis-data-relationalStore.md new file mode 100644 index 0000000000000000000000000000000000000000..1d3451af2d899c34d1b73f2669c688cac7d6f464 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md @@ -0,0 +1,3202 @@ +# @ohos.data.relationalStore + +The relational database (RDB) store manages data based on relational models. With the underlying SQLite database, the RDB store provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB store offers a series of APIs for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. + +The **relationalStore** module provides the following functions: + +- [RdbPredicates](#rdbpredicates): provides predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. +- [RdbStore](#rdbstore): provides APIs for managing data in an RDB store. +- [Resultset](#resultset): provides APIs for accessing the result set obtained from the RDB store. + +> **NOTE**
+> +> 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. + +## Modules to Import + +```js +import data_rdb from '@ohos.data.relationalStore'; +``` + +## data_rdb.getRdbStore + +getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void + +Obtains an RDB store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes | Callback invoked to return the RDB store obtained. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | +| 14800011 | If failed open database by database corrupted. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 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_CREATA) { + console.log("RdbStore status is ON_CREATA") + } else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) { + console.log("RdbStore status is ON_OPEN") + } else { + return + } + console.log("Got RdbStore successfully.") +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 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_CREATA) { + console.log("RdbStore status is ON_CREATA") + } 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 + +getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> + +Obtains an RDB store. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | + +**Return value** + +| Type | Description | +| ----------------------------------------- | --------------------------------- | +| Promise<[RdbStore](#rdbstore)> | Promise used to return the RDB store obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | +| 14800011 | If failed open database by database corrupted. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 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_CREATA) { + console.log("RdbStore status is ON_CREATA") + } 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) +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 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_CREATA) { + console.log("RdbStore status is ON_CREATA") + } 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 + +deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void + +Deletes an RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 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.") +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 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 + +deleteRdbStore(context: Context, name: string): Promise<void> + +Deletes an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------- | +| 14800010 | If failed delete database by invalid database name. | + +**Example** + +FA model: + +```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() + +// 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) +}) +``` + +Stage model: + +```ts +// Obtain the context. +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// 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 + +Defines the RDB store configuration. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------- | ------------- | ---- | --------------------------------------------------------- | +| name | string | Yes | Database file name. | +| securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the RDB store. | +| encrypt | boolean | No | Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store;
the value **false** means the opposite.| + +## SecurityLevel + +Enumerates the RDB store security levels. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Value | Description | +| ---- | ---- | ------------------------------------------------------------ | +| S1 | 1 | The RDB store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, an RDB store that contains system data such as wallpapers.| +| S2 | 2 | The RDB store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, an RDB store that contains information created by users or call records, such as audio or video clips.| +| S3 | 3 | The RDB store security level is high. If data leakage occurs, major impact will be caused on the database. For example, an RDB store that contains information such as user fitness, health, and location data.| +| S4 | 4 | The RDB store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, an RDB store that contains information such as authentication credentials and financial data.| + +## ValueType + +Defines the data types allowed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Type | Description | +| ------- | -------------------- | +| number | Number. | +| string | String. | +| boolean | Boolean.| + +## ValuesBucket + +Defines the types of the key and value in a KV pair. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Key Type| Value Type | +| ------ | ----------------------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | + +## SyncMode + +Defines the database synchronization mode. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| -------------- | ---- | ---------------------------------- | +| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| +| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device. | + +## SubscribeType + +Defines the subscription type. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------------ | +| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| + +## ConflictResolution10+ + +Defines the resolution to use when **insert()** and **update()** conflict. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| -------------------- | ---- | ------------------------------------------------------------ | +| ON_CONFLICT_NONE | 0 | No operation is performed.| +| ON_CONFLICT_ROLLBACK | 1 | Abort the SQL statement and roll back the current transaction. | +| ON_CONFLICT_ABORT | 2 | Abort the current SQL statement and revert any changes made by the current SQL statement. However, the changes made by the previous SQL statement in the same transaction are retained and the transaction remains active.| +| ON_CONFLICT_FAIL | 3 | Abort the current SQL statement. The **FAIL** resolution does not revert previous changes made by the failed SQL statement or end the transaction.| +| 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.| + +## OpenStatus10+ + +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 + +Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. + +### constructor + +constructor(name: string) + +A constructor used to create an **RdbPredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| name | string | Yes | Database table name.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +``` + +### inDevices + +inDevices(devices: Array<string>): RdbPredicates + + +Sets an **RdbPredicates** to specify the remote devices to connect on the network during distributed database synchronization. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | -------------------------- | +| devices | Array<string> | Yes | IDs of the remote devices in the same network.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inDevices(['12345678abcde']) +``` + +### inAllDevices + +inAllDevices(): RdbPredicates + + +Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.inAllDevices() +``` + +### equalTo + +equalTo(field: string, value: ValueType): RdbPredicates + + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") +``` + + +### notEqualTo + +notEqualTo(field: string, value: ValueType): RdbPredicates + + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notEqualTo("NAME", "lisi") +``` + + +### beginWrap + +beginWrap(): RdbPredicates + + +Adds a left parenthesis to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### endWrap + +endWrap(): RdbPredicates + +Adds a right parenthesis to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### or + +or(): RdbPredicates + +Adds the OR condition to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") +``` + +### and + +and(): RdbPredicates + +Adds the AND condition to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) +``` + +### contains + +contains(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string containing the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.contains("NAME", "os") +``` + +### beginsWith + +beginsWith(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that starts with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.beginsWith("NAME", "os") +``` + +### endsWith + +endsWith(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that ends with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.endsWith("NAME", "se") +``` + +### isNull + +isNull(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the field whose value is null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNull("NAME") +``` + +### isNotNull + +isNotNull(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the field whose value is not null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.isNotNull("NAME") +``` + +### like + +like(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that is similar to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.like("NAME", "%os%") +``` + +### glob + +glob(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match the specified string. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.

Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.glob("NAME", "?h*g") +``` + +### between + +between(field: string, low: ValueType, high: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | Yes | Column name in the database table. | +| low | [ValueType](#valuetype) | Yes | Minimum value to match the **RdbPredicates**. | +| high | [ValueType](#valuetype) | Yes | Maximum value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.between("AGE", 10, 50) +``` + +### notBetween + +notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | Yes | Column name in the database table. | +| low | [ValueType](#valuetype) | Yes | Minimum value to match the **RdbPredicates**. | +| high | [ValueType](#valuetype) | Yes | Maximum value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notBetween("AGE", 10, 50) +``` + +### greaterThan + +greaterThan(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThan("AGE", 18) +``` + +### lessThan + +lessThan(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThan("AGE", 20) +``` + +### greaterThanOrEqualTo + +greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.greaterThanOrEqualTo("AGE", 18) +``` + +### lessThanOrEqualTo + +lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.lessThanOrEqualTo("AGE", 20) +``` + +### orderByAsc + +orderByAsc(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the column with values sorted in ascending order. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByAsc("NAME") +``` + +### orderByDesc + +orderByDesc(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the column with values sorted in descending order. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.orderByDesc("AGE") +``` + +### distinct + +distinct(): RdbPredicates + +Sets an **RdbPredicates** to filter out duplicate records. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").distinct() +``` + +### limitAs + +limitAs(value: number): RdbPredicates + +Sets an **RdbPredicates** to specify the maximum number of records. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| value | number | Yes | Maximum number of records.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").limitAs(3) +``` + +### offsetAs + +offsetAs(rowOffset: number): RdbPredicates + +Sets an **RdbPredicates** to specify the start position of the returned result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------------------------------- | +| rowOffset | number | Yes | Number of rows to offset from the beginning. The value is a positive integer.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose").offsetAs(3) +``` + +### groupBy + +groupBy(fields: Array<string>): RdbPredicates + +Sets an **RdbPredicates** to group rows that have the same value into summary rows. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | -------------------- | +| fields | Array<string> | Yes | Names of columns to group.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ---------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.groupBy(["AGE", "NAME"]) +``` + +### indexedBy + +indexedBy(field: string): RdbPredicates + +Sets an **RdbPredicates** object to specify the index column. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| field | string | Yes | Name of the index column.| + +**Return value** + + +| Type | Description | +| ------------------------------------ | ------------------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.indexedBy("SALARY_INDEX") +``` + +### in + +in(field: string, value: Array<ValueType>): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | --------------------------------------- | +| field | string | Yes | Column name in the database table. | +| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.in("AGE", [18, 20]) +``` + +### notIn + +notIn(field: string, value: Array<ValueType>): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | ------------------------------------- | +| field | string | Yes | Column name in the database table. | +| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.notIn("NAME", ["Lisa", "Rose"]) +``` + +## RdbStore + +Provides methods to manage an RDB store. + +Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). + +### Attributes10+ + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------ | ----------- | ---- | -------------------------------- | +| openStatus10+ | 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. | + +### insert + +insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void + +Inserts a row of data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ---------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { + if (status) { + console.log("Failed to insert data"); + return; + } + console.log("Inserted data successfully, rowId = " + rowId); +}) +``` + +### insert10+ + +insert(table: string, values: ValuesBucket, conflict: ConflictResolution, callback: AsyncCallback<number>):void + +Inserts a row of data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ---------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +rdbStore.insert("EMPLOYEE", valueBucket, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE, function (status, rowId) { + if (status) { + console.log("Failed to insert data"); + return; + } + console.log("Inserted data successfully, rowId = " + rowId); +}) +``` + +### insert + +insert(table: string, values: ValuesBucket):Promise<number> + +Inserts a row of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let promise = rdbStore.insert("EMPLOYEE", valueBucket) +promise.then((rowId) => { + console.log("Inserted data successfully, rowId = " + rowId); +}).catch((status) => { + console.log("Failed to insert data"); +}) +``` + +### insert10+ + +insert(table: string, values: ValuesBucket, conflict: ConflictResolution):Promise<number> + +Inserts a row of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert.| +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Example** + +```js +const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let promise = rdbStore.insert("EMPLOYEE", valueBucket, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE) +promise.then((rowId) => { + console.log("Inserted data successfully, rowId = " + rowId); +}).catch((status) => { + console.log("Failed to insert data"); +}) +``` + +### batchInsert + +batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void + +Batch inserts data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Example** + +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { + if (status) { + console.log("batchInsert is failed, status = " + status); + return; + } + console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +}) +``` + +### batchInsert + +batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> + +Batch inserts data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Example** + +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); +promise.then((insertNum) => { + console.log("batchInsert is successful, the number of values that were inserted = " + insertNum); +}).catch((status) => { + console.log("batchInsert is failed, status = " + status); +}) +``` + +### update + +update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void + +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | + +**Example** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.update(valueBucket, predicates, function (err, rows) { + if (err) { + console.info("Failed to update data, err: " + err) + return + } + console.log("Updated row count: " + rows) +}) +``` + +### update10+ + +update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution, callback: AsyncCallback<number>):void + +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | + +**Example** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.update(valueBucket, predicates, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE, function (err, rows) { + if (err) { + console.info("Failed to update data, err: " + err) + return + } + console.log("Updated row count: " + rows) +}) +``` + +### update + +update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> + +Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update(valueBucket, predicates) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Failed to update data, err: " + err) +}) +``` + +### update10+ + +update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution):Promise<number> + +Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** + +```js +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update(valueBucket, predicates, data_rdb.ConflictResolution.ON_CONFLICT_REPLACE) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Failed to update data, err: " + err) +}) +``` + +### update + +update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void + +Updates data based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Update conditions specified by the **DataSharePredicates** object. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, rows) { + if (err) { + console.info("Failed to update data, err: " + err) + return + } + console.log("Updated row count: " + rows) +}) +``` + +### update + +update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> + +Updates data based on the specified **DataSharePredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Update conditions specified by the **DataSharePredicates** object. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), +} +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) +}).catch((err) => { + console.info("Failed to update data, err: " + err) +}) +``` + +### delete + +delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void + +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows deleted. | + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +rdbStore.delete(predicates, function (err, rows) { + if (err) { + console.info("Failed to delete data, err: " + err) + return + } + console.log("Deleted rows: " + rows) +}) +``` + +### delete + +delete(predicates: RdbPredicates):Promise<number> + +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise<number> | Promise used to return the number of rows deleted.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete(predicates) +promise.then((rows) => { + console.log("Deleted rows: " + rows) +}).catch((err) => { + console.info("Failed to delete data, err: " + err) +}) +``` + +### delete + +delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void + +Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions specified by the **DataSharePredicates** object for deleting data.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows deleted. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { + if (err) { + console.info("Failed to delete data, err: " + err) + return + } + console.log("Deleted rows: " + rows) +}) +``` + +### delete + +delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise<number> + +Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Conditions specified by the **DataSharePredicates** object for deleting data.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise<number> | Promise used to return the number of rows deleted.| + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Lisa") +let promise = rdbStore.delete("EMPLOYEE", predicates) +promise.then((rows) => { + console.log("Deleted rows: " + rows) +}).catch((err) => { + console.info("Failed to delete data, err: " + err) +}) +``` + +### query + +query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void + +Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose") +rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.info("Failed to query data, err: " + err) + return + } + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### query + +query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> + +Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + + ```js +let predicates = new data_rdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("NAME", "Rose") +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to query data, err: " + err) +}) + ``` + +### query + +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void + +Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Query conditions specified by the **DataSharePredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + if (err) { + console.info("Failed to query data, err: " + err) + return + } + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### query + +query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> + +Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Query conditions specified by the **DataSharePredicates** object. | +| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates' +let predicates = new dataSharePredicates.DataSharePredicates() +predicates.equalTo("NAME", "Rose") +let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to query data, err: " + err) +}) +``` + +### remoteQuery + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void + +Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| device | string | Yes | Network ID of the remote device. | +| table | string | Yes | Name of the target table. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.greaterThan("id", 0) +rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], + function(err, resultSet){ + if (err) { + console.info("Failed to remoteQuery, err: " + err) + return + } + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### remoteQuery + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> + +Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| device | string | Yes | Network ID of the remote device. | +| table | string | Yes | Name of the target table. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.greaterThan("id", 0) +let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to remoteQuery , err: " + err) +}) +``` + +### querySql + +querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void + +Queries data using the specified SQL statement. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { + if (err) { + console.info("Failed to query data, err: " + err) + return + } + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### querySql + +querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> + +Queries data using the specified SQL statement. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | Yes | SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) +promise.then((resultSet) => { + console.log("ResultSet column names: " + resultSet.columnNames) + console.log("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to query data, err: " + err) +}) +``` + +### executeSql + +executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void + +Executes an SQL statement that contains specified arguments but returns no value. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ---------------------- | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + +```js +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { + if (err) { + console.info("Failed to execute SQL, err: " + err) + return + } + console.info('Create table done.') +}) +``` + +### executeSql + +executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> + +Executes an SQL statement that contains specified arguments but returns no value. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | --------------------- | +| sql | string | Yes | SQL statement to run.| +| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" +let promise = rdbStore.executeSql(SQL_CREATE_TABLE) +promise.then(() => { + console.info('Create table done.') +}).catch((err) => { + console.info("Failed to execute SQL, err: " + err) +}) +``` + +### beginTransaction + +beginTransaction():void + +Starts the transaction before executing an SQL statement. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() +}) +``` + +### commit + +commit():void + +Commits the executed SQL statements. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() +}) +``` + +### rollBack + +rollBack():void + +Rolls back the SQL statements that have been executed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility' +let context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db", + securityLevel: data_rdb.SecurityLevel.S1} +data_rdb.getRdbStore(context, STORE_CONFIG, async function (err, rdbStore) { + try { + rdbStore.beginTransaction() + const valueBucket = { + "id": 1, + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() + } catch (e) { + rdbStore.rollBack() + } +}) +``` + +### backup + +backup(destName:string, callback: AsyncCallback<void>):void + +Backs up an RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| destName | string | Yes | Name of the RDB store backup file.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +rdbStore.backup("dbBackup.db", function(err) { + if (err) { + console.info('Backup failed, err: ' + err) + return + } + console.info('Backup success.') +}) +``` + +### backup + +backup(destName:string): Promise<void> + +Backs up an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------ | +| destName | string | Yes | Name of the RDB store backup file.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promiseBackup = rdbStore.backup("dbBackup.db") +promiseBackup.then(()=>{ + console.info('Backup success.') +}).catch((err)=>{ + console.info('Backup failed, err: ' + err) +}) +``` + +### restore + +restore(srcName:string, callback: AsyncCallback<void>):void + +Restores an RDB store from a backup file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| srcName | string | Yes | Name of the RDB store backup file.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +rdbStore.restore("dbBackup.db", function(err) { + if (err) { + console.info('Restore failed, err: ' + err) + return + } + console.info('Restore success.') +}) +``` + +### restore + +restore(srcName:string): Promise<void> + +Restores an RDB store from a backup file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------ | +| srcName | string | Yes | Name of the RDB store backup file.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promiseRestore = rdbStore.restore("dbBackup.db") +promiseRestore.then(()=>{ + console.info('Restore success.') +}).catch((err)=>{ + console.info('Restore failed, err: ' + err) +}) +``` + +### setDistributedTables + +setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void + +Sets distributed tables. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------- | +| tables | Array<string> | Yes | Names of the distributed tables to set.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + +```js +rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { + if (err) { + console.info('Failed to set distributed tables, err: ' + err) + return + } + console.info('Set distributed tables successfully.') +}) +``` + +### setDistributedTables + + setDistributedTables(tables: Array<string>): Promise<void> + +Sets distributed tables. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | ------------------------ | +| tables | Array<string> | Yes | Names of the distributed tables to set.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) +promise.then(() => { + console.info("Set distributed tables successfully.") +}).catch((err) => { + console.info("Failed to set distributed tables, err: " + err) +}) +``` + +### obtainDistributedTableName + +obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void + +Obtains the distributed table name for a remote device based on the local table name. This API uses an asynchronous callback to return the result. The distributed table name is required when the RDB store of a remote device is queried. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| device | string | Yes | Remote device. | +| table | string | Yes | Local table name. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| + +**Example** + +```js +rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { + if (err) { + console.info('Failed to obtain DistributedTableName, err: ' + err) + return + } + console.info('Obtained distributed table name successfully, tableName=.' + tableName) +}) +``` + +### obtainDistributedTableName + + obtainDistributedTableName(device: string, table: string): Promise<string> + +Obtains the distributed table name for a remote device based on the local table name. This API uses a promise to return the result. The distributed table name is required when the RDB store of a remote device is queried. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| device | string | Yes | Remote device.| +| table | string | Yes | Local table name.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------------- | +| Promise<string> | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| + +**Example** + +```js +let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") +promise.then((tableName) => { + console.info('Obtained distributed table name successfully, tableName= ' + tableName) +}).catch((err) => { + console.info('Failed to obtain DistributedTableName, err: ' + err) +}) +``` + +### sync + +sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void + +Synchronizes data between devices. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| mode | [SyncMode](#syncmode) | Yes | Data synchronization mode. The value can be **push** or **pull**. | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | **RdbPredicates** object that specifies the data and devices to synchronize. | +| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.inDevices(['12345678abcde']) +rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, result) { + if (err) { + console.log('Sync failed, err: ' + err) + return + } + console.log('Sync done.') + for (let i = 0; i < result.length; i++) { + console.log('device=' + result[i][0] + ' status=' + result[i][1]) + } +}) +``` + +### sync + + sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>> + +Synchronizes data between devices. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------ | +| mode | [SyncMode](#syncmode) | Yes | Data synchronization mode. The value can be **push** or **pull**.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | **RdbPredicates** object that specifies the data and devices to synchronize. | + +**Return value** + +| Type | Description | +| -------------------------------------------- | ------------------------------------------------------------ | +| Promise<Array<[string, number]>> | Promise used to send the synchronization result.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | + +**Example** + +```js +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') +predicates.inDevices(['12345678abcde']) +let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates) +promise.then((resultSet) =>{ + console.log('Sync done.') + for (let i = 0; i < resultSet.length; i++) { + console.log('device=' + resultSet[i][0] + ' status=' + resultSet[i][1]) + } +}).catch((err) => { + console.log('Sync failed') +}) +``` + +### on('dataChange') + +on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +Registers an observer for this RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------------------------- | +| event | string | Yes | The value is'dataChange', which indicates a data change event. | +| type | [SubscribeType](#subscribetype) | Yes | Subscription type to register.| +| observer | Callback<Array<string>> | Yes | Observer that listens for the data changes in the RDB store. | + +**Example** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Failed to register observer') +} +``` + +### off('dataChange') + +off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void + +Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------ | +| event | string | Yes | The value is'dataChange', which indicates a data change event. | +| type | [SubscribeType](#subscribetype) | Yes | Subscription type to register. | +| observer | Callback<Array<string>> | Yes | Data change observer registered. | + +**Example** + +```js +function storeObserver(devices) { + for (let i = 0; i < devices.length; i++) { + console.log('device=' + devices[i] + ' data changed') + } +} +try { + rdbStore.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) +} catch (err) { + console.log('Failed to unregister observer') +} +``` + +## ResultSet + +Provides APIs to access the result set obtained by querying the RDB store. A result set is a set of results returned after **query()** is called. + +### Usage + +Obtain the **resultSet** object by [RdbStore.query()](#query). + +```js +import dataRdb from '@ohos.data.rdb'; +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +predicates.equalTo("AGE", 18); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); + console.log(TAG + "resultSet columnCount:" + resultSet.columnCount); +}); +``` + +### Attributes + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------ | ------------------- | ---- | -------------------------------- | +| columnNames | Array<string> | Yes | Names of all columns in the result set. | +| columnCount | number | Yes | Number of columns in the result set. | +| rowCount | number | Yes | Number of rows in the result set. | +| rowIndex | number | Yes | Index of the current row in the result set. | +| isAtFirstRow | boolean | Yes | Whether the cursor is in the first row of the result set. | +| isAtLastRow | boolean | Yes | Whether the cursor is in the last row of the result set. | +| isEnded | boolean | Yes | Whether the cursor is after the last row of the result set.| +| isStarted | boolean | Yes | Whether the cursor has been moved. | +| isClosed | boolean | Yes | Whether the result set is closed. | + +### getColumnIndex + +getColumnIndex(columnName: string): number + +Obtains the column index based on the column name. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | -------------------------- | +| columnName | string | Yes | Column name.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Column index obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + + ```js +resultSet.goToFirstRow(); +const id = resultSet.getLong(resultSet.getColumnIndex("ID")); +const name = resultSet.getString(resultSet.getColumnIndex("NAME")); +const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); +const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); + ``` + +### getColumnName + +getColumnName(columnIndex: number): string + +Obtains the column name based on the specified column index. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | -------------------------- | +| columnIndex | number | Yes | Column index.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Column name obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + + ```js +const id = resultSet.getColumnName(0); +const name = resultSet.getColumnName(1); +const age = resultSet.getColumnName(2); + ``` + +### goTo + +goTo(offset:number): boolean + +Moves the cursor to the row based on the specified offset. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| offset | number | Yes | Offset relative to the current position.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise= rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goTo(1); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToRow + +goToRow(position: number): boolean + +Moves to the specified row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------ | +| position | number | Yes | Destination position to move to.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.(5); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToFirstRow + +goToFirstRow(): boolean + + +Moves to the first row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToFirstRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToLastRow + +goToLastRow(): boolean + +Moves to the last row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToLastRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToNextRow + +goToNextRow(): boolean + +Moves to the next row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToNextRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### goToPreviousRow + +goToPreviousRow(): boolean + +Moves to the previous row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + + ```js +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promise.then((resultSet) => { + resultSet.goToPreviousRow(); + resultSet.close(); +}).catch((err) => { + console.log('query failed'); +}); + ``` + +### getBlob + +getBlob(columnIndex: number): Uint8Array + +Obtains the value in the form of a byte array based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ---------- | -------------------------------- | +| Uint8Array | Value obtained.| + +**Example** + + ```js +const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); + ``` + +### getString + +getString(columnIndex: number): string + +Obtains the value in the form of a string based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| string | String obtained.| + +**Example** + + ```js +const name = resultSet.getString(resultSet.getColumnIndex("NAME")); + ``` + +### getLong + +getLong(columnIndex: number): number + +Obtains the value of the Long type based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| number | Value obtained.| + +**Example** + + ```js +const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); + ``` + +### getDouble + +getDouble(columnIndex: number): number + +Obtains the value of the double type based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| number | Value obtained.| + +**Example** + + ```js +const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); + ``` + +### isColumnNull + +isColumnNull(columnIndex: number): boolean + +Checks whether the value in the specified column is null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------------------- | +| boolean | Returns **true** if the value is null; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + + ```js +const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); + ``` + +### close + +close(): void + +Closes this result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + + ```js +let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE"); +let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); +promiseClose.then((resultSet) => { + resultSet.close(); +}).catch((err) => { + console.log('resultset close failed'); +}); + ``` + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | diff --git a/en/application-dev/reference/errorcodes/errorcode-datashare.md b/en/application-dev/reference/errorcodes/errorcode-datashare.md new file mode 100644 index 0000000000000000000000000000000000000000..1dae1ebbae1af4b9940ffa6a81e9130eeaa4a94d --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-datashare.md @@ -0,0 +1,21 @@ +# DataShare Error Codes + +## 15700010 Failed to Create a DataShareHelper + +**Error Message** + +The dataShareHelper is not initialized successfully. + +**Description** + +The **DataShareHelper** class fails to be created. + +**Possible Causes** + +1. The **uri** specified in **createDataHelper** is incorrect. +2. The **context** specified in **createDataHelper** is incorrect. **DataShare** supports only the stage model. + +**Solution** + +1. Obtain the correct URI. +2. Check that the context of the stage model is used.