目录

@ohos.data.rdb (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. The worker threads are not supported.

This module provides the following RDB-related functions:

  • 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.

Modules to Import

import data_rdb from '@ohos.data.rdb';

data_rdb.getRdbStore

getRdbStore(context: Context, config: StoreConfig, version: number, 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.

For details about the application context of the stage model, see Context.

config 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> Yes Callback invoked when the operation is successful, in which case err is undefined and data is the RdbStore object; otherwise, it is an error object.

Example

FA model:

import featureAbility from '@ohos.ability.featureAbility';
import relationalStore from '@ohos.data.relationalStore';
import window from '@ohos.window';
import { BusinessError } from '@ohos.base';

const STORE_CONFIG: data_rdb.StoreConfig = { name: "RdbTest.db"}
data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, (err, rdbStore) => {
  if (err) {
    console.error("Get RdbStore failed, err: " + err)
    return
  }
  console.info("Get RdbStore successfully.")
})

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from "@ohos.base";
import window from '@ohos.window';

const STORE_CONFIG: data_rdb.StoreConfig = { name: "RdbTest.db"}
class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage){
    data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, (err: BusinessError, rdbStore: data_rdb.RdbStore) => {
      if (err) {
        console.error("Get RdbStore failed, err: " + err)
        return
      }
      console.info("Get RdbStore successfully.")
    })
  }
}

data_rdb.getRdbStore

getRdbStore(context: Context, config: StoreConfig, version: number): 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.

For details about the application context of the stage model, see Context.

config 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
Promise<RdbStore> Promise used to return the RdbStore object.

Example

FA model:

import featureAbility from '@ohos.ability.featureAbility';

const STORE_CONFIG: data_rdb.StoreConfig = { name: "RdbTest.db"}
let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG, 1);
promise.then(async (rdbStore) => {
  console.info("Get RdbStore successfully.")
}).catch((err: BusinessError) => {
  console.error("Get RdbStore failed, err: " + err)
})

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from "@ohos.base";
import window from '@ohos.window';

const STORE_CONFIG: data_rdb.StoreConfig = { name: "RdbTest.db"}
class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage){
    context = this.context
  }
}

// Call getRdbStore.
let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG, 1);
promise.then(async (rdbStore: data_rdb.RdbStore) => {
  console.info("Get RdbStore successfully.")
}).catch((err: BusinessError) => {
  console.error("Get RdbStore failed, 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.

For details about the application context of the stage model, see Context.

name string Yes Database name, which cannot be empty and cannot contain the path separator /.
callback AsyncCallback<void> Yes Callback invoked when the operation succeeds, err is undefined; otherwise, it is an error object.

Example

FA model:

import featureAbility from '@ohos.ability.featureAbility';

data_rdb.deleteRdbStore(this.context, "RdbTest.db", (err) => {
  if (err) {
    console.error("Delete RdbStore failed, err: " + err)
    return
  }
  console.info("Delete RdbStore successfully.")
})

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';

class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage){
    context = this.context
  }
}

// Call deleteRdbStore.
data_rdb.deleteRdbStore(this.context, "RdbTest.db", (err) => {
  if (err) {
    console.error("Delete RdbStore failed, err: " + err)
    return
  }
  console.info("Delete 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.

For details about the application context of the stage model, see Context.

name string Yes Database name, which cannot be empty and cannot contain the path separator /.

Return value

Type Description
Promise<void> Promise that returns no value.

Example

FA model:

import featureAbility from '@ohos.ability.featureAbility';

let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db")
promise.then(() => {
  console.info("Delete RdbStore successfully.")
}).catch((err: BusinessError) => {
  console.error("Delete RdbStore failed, err: " + err)
})

Stage model:

import UIAbility from '@ohos.app.ability.UIAbility';
import { BusinessError } from "@ohos.base";
import window from '@ohos.window';

class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage){
    context = this.context
  }
}

// Call deleteRdbStore.
let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db")
promise.then(()=>{
  console.info("Delete RdbStore successfully.")
}).catch((err: BusinessError) => {
  console.error("Delete RdbStore failed, err: " + err)
})

ValueType

type ValueType = number | string | boolean

Defines the data types allowed.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Type Description
number Number.
string String.
boolean Boolean.

ValuesBucket

type ValuesBucket = { [key: string]: ValueType | Uint8Array | null }

Defines the types of the key and value in a KV pair.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Key Type Value Type
string ValueType| Uint8Array | null

SyncMode8+

Defines the database sync 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, which cannot be an empty string and cannot contain the path separator /.

RdbPredicates

Defines predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false.

[h2]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. It cannot be an empty string.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")

[h2]inDevices8+

inDevices(devices: Array<string>): RdbPredicates

Creates an RdbPredicates object to specify the remote devices to connect on the network during distributed database sync.

The value of devices can be obtained by using deviceManager.getTrustedDeviceListSync. The APIs of the deviceManager module are system interfaces and available only to system applications.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
devices Array<string> Yes ID of the remote device in the specified network. Cannot be empty.

Return value

Type Description
RdbPredicates Predicate configured with the synchronization condition of the specified remote device.

Example

import deviceManager from '@ohos.distributedHardware.deviceManager';

let dmInstance: deviceManager.DeviceManager;
let deviceIds: Array<string> = [];
let devices: Array<string> = [];

deviceManager.createDeviceManager("com.example.appdatamgrverify", (err: BusinessError, manager: void) => {
  if (err) {
    console.error("create device manager failed, err=" + err);
    return;
  }
  dmInstance = manager;
  devices = dmInstance.getTrustedDeviceListSync();
  for (let i = 0; i < devices.length; i++) {
    deviceIds[i] = devices[i].deviceId;
  }
})
                                  
let predicates = new data_rdb.RdbPredicates("EMPLOYEE");
predicates.inDevices(deviceIds);

[h2]inAllDevices8+

inAllDevices(): RdbPredicates

Creates an RdbPredicates object to specify all remote devices on the network to connect during distributed database sync.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Return value

Type Description
RdbPredicates Predicate configured with synchronization conditions for all remote devices.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.inAllDevices()

[h2]equalTo

equalTo(field: string, value: ValueType): RdbPredicates

Configures the predicate to match the field whose data field is ValueType and whose value is equal to the specified value. This method is equivalent to "=" in an SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value ValueType Yes Value to match.

Return value

Type Description
RdbPredicates Predicate configured with a condition equal to the specified value.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "lisi")

[h2]notEqualTo

notEqualTo(field: string, value: ValueType): RdbPredicates

Configures the predicate to match the field whose data field is ValueType and whose value is not equal to the specified value. This method is equivalent to "!=" in an SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value ValueType Yes Value to match.

Return value

Type Description
RdbPredicates Predicate configured with the condition that the value is not equal to the specified value.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.notEqualTo("NAME", "lisi")

[h2]beginWrap

beginWrap(): RdbPredicates

Creates an RdbPredicates object to add a left parenthesis.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Return value

Type Description
RdbPredicates RdbPredicates object created.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "lisi")
    .beginWrap()
    .equalTo("AGE", 18)
    .or()
    .equalTo("SALARY", 200.5)
    .endWrap()

[h2]endWrap

endWrap(): RdbPredicates

Creates an RdbPredicates object to add a right parenthesis.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Return value

Type Description
RdbPredicates RdbPredicates created.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "lisi")
    .beginWrap()
    .equalTo("AGE", 18)
    .or()
    .equalTo("SALARY", 200.5)
    .endWrap()

[h2]or

or(): RdbPredicates

Creates an RdbPredicates object to add the OR condition.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Return value

Type Description
RdbPredicates RdbPredicates created.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa")
    .or()
    .equalTo("NAME", "Rose")

[h2]and

and(): RdbPredicates

Creates an RdbPredicates object to add the AND condition.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Return value

Type Description
RdbPredicates RdbPredicates object created.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa")
    .and()
    .equalTo("SALARY", 200.5)

[h2]contains

contains(field: string, value: string): RdbPredicates

Configures the predicate to match the field whose data field is string and whose value contains the specified value. This method is equivalent to "LIKE '%xxx%'" in an SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value string Yes Value to match against the predicate, with a length not exceeding 1024 bytes.

Return value

Type Description
RdbPredicates Predicate configured with the condition of containing the specified value.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.contains("NAME", "os")

[h2]beginsWith

beginsWith(field: string, value: string): RdbPredicates

Configures the predicate to match the field whose data field is string and whose value starts with the specified string. This method is equivalent to "LIKE 'xxx%'" in an SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value string Yes Value to match against the predicate, with a length not exceeding 1024 bytes.

Return value

Type Description
RdbPredicates Predicate configured with the condition that starts with a specified string.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.beginsWith("NAME", "os")

[h2]endsWith

endsWith(field: string, value: string): RdbPredicates

Configures the predicate to match the field whose data field is string and whose value ends with the specified string. This method is equivalent to "LIKE '%xxx'" in an SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value string Yes Value to match against the predicate, with a length not exceeding 1024 bytes.

Return value

Type Description
RdbPredicates Predicate with the condition that ends with the specified string.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.endsWith("NAME", "se")

[h2]isNull

isNull(field: string): RdbPredicates

Configures the predicate to match the field whose value is null. This method is equivalent to "IS NULL" in an SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.

Return value

Type Description
RdbPredicates Predicate configured with a null value condition.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.isNull("NAME")

[h2]isNotNull

isNotNull(field: string): RdbPredicates

Configures the predicate to match the specified field whose value is not null. This method is equivalent to "IS NOT NULL" in an SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.

Return value

Type Description
RdbPredicates Predicate configured with a non-null value condition.

Error codes

For details about the error codes, see Universal Error Codes.

Error Code Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.isNotNull("NAME")

[h2]like

like(field: string, value: string): RdbPredicates

Configures the predicate to match the field whose data field is string and whose value is similar to the specified string. This method is equivalent to "LIKE" in an SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value string Yes Value to match against the predicate, with a length not exceeding 1024 bytes.

Return value

Type Description
RdbPredicates Predicate configured with a condition similar to the specified string.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.like("NAME", "%os%")

[h2]glob

glob(field: string, value: string): RdbPredicates

Creates an RdbPredicates to match the fields whose data type is string and whose value matches the specified wildcard pattern, where * matches any number of characters and ? matches a single character. This method is equivalent to GLOB in SQL statements.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value string Yes

Value to match with the predicate. The length cannot exceed 1024 bytes.

Wildcards are supported, where * indicates 0, 1, or multiple digits or characters, and ? indicates 1 digit or character.

Return value

Type Description
RdbPredicates Predicate configured to match the specified wildcard pattern.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.glob("NAME", "?h*g")

[h2]between

between(field: string, low: ValueType, high: ValueType): RdbPredicates

Configures the predicate to match the specified field whose data field is ValueType and whose value is within the given range. This method is equivalent to "BETWEEN" in an SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
low ValueType Yes Minimum value of the range to set.
high ValueType Yes Maximum value of the range to set.

Return value

Type Description
RdbPredicates Predicates configured with conditions within the given range.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.between("AGE", 10, 50)

[h2]notBetween

notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates

Configures the RdbPredicates to match the specified field whose data field is of the ValueType type and whose value is outside the given range. This method is equivalent to "NOT BETWEEN" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
low ValueType Yes Minimum value of the range to set.
high ValueType Yes Maximum value of the range to set.

Return value

Type Description
RdbPredicates Predicates configured with conditions beyond the given range.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.notBetween("AGE", 10, 50)

[h2]greaterThan

greaterThan(field: string, value: ValueType): RdbPredicates

Configures the predicate to match the field whose data field is of the ValueType type and whose value is greater than the specified value. This method is equivalent to ">" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value ValueType Yes Value to match.

Return value

Type Description
RdbPredicates Predicate configured with the greater-than-specified-value condition.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.greaterThan("AGE", 18)

[h2]lessThan

lessThan(field: string, value: ValueType): RdbPredicates

Configures the predicate to match the field whose data field is of the ValueType type and whose value is less than the specified value. This method is equivalent to "<" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value ValueType Yes Value to match.

Return value

Type Description
RdbPredicates Predicate configured with the condition of being less than the specified value.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.lessThan("AGE", 20)

[h2]greaterThanOrEqualTo

greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates

Configures the predicate to match the field whose data field is of the ValueType type and whose value is greater than or equal to the specified value. This method is equivalent to ">=" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value ValueType Yes Value to match.

Return value

Type Description
RdbPredicates Predicate configured with the condition that a value is greater than or equal to the specified value.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.greaterThanOrEqualTo("AGE", 18)

[h2]lessThanOrEqualTo

lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates

Configures the predicate to match the field whose data field is of the ValueType type and whose value is less than or equal to the specified value. This method is equivalent to "<=" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value ValueType Yes Value to match.

Return value

Type Description
RdbPredicates Predicate configured with the condition that the value is less than or equal to the specified value.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.lessThanOrEqualTo("AGE", 20)

[h2]orderByAsc

orderByAsc(field: string): RdbPredicates

Configures the predicate to match the column whose values are sorted in ascending order. This method is equivalent to "ORDER BY" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.

Return value

Type Description
RdbPredicates Predicate configured with the ascending sort condition.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.orderByAsc("NAME")

[h2]orderByDesc

orderByDesc(field: string): RdbPredicates

Configures the predicate to match the column whose values are sorted in descending order. This method is equivalent to "ORDER BY" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.

Return value

Type Description
RdbPredicates Predicate configured with a descending sort condition.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.orderByDesc("AGE")

[h2]distinct

distinct(): RdbPredicates

Configures the predicate to filter out duplicate records and keep only one of them. This method is equivalent to "DISTINCT" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Return value

Type Description
RdbPredicates RdbPredicates object created.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").distinct()

[h2]limitAs

limitAs(value: number): RdbPredicates

Sets the predicate for the maximum number of data records. This method is equivalent to "LIMIT" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
value number Yes Maximum number of records.

Return value

Type Description
RdbPredicates RdbPredicates object created.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").limitAs(3)

[h2]offsetAs

offsetAs(rowOffset: number): RdbPredicates

Configures the RdbPredicates to specify the start position of the returned result. You need to call the limitAs API synchronously to specify the number of records to query; otherwise, no query result will be returned. To query all rows after the specified offset position, pass -1 to the limitAs API. This method is equivalent to "OFFSET" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
rowOffset number Yes Start position, which is a positive integer.

Return value

Type Description
RdbPredicates RdbPredicates object created.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose").limitAs(-1).offsetAs(3)

[h2]groupBy

groupBy(fields: Array<string>): RdbPredicates

Configures RdbPredicates to group query results by the specified columns. This method is equivalent to "GROUP BY" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
fields Array<string> Yes Column names on which the grouping depends. They cannot be empty strings.

Return value

Type Description
RdbPredicates RdbPredicates object created.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.groupBy(["AGE", "NAME"])

[h2]indexedBy

indexedBy(field: string): RdbPredicates

Configures RdbPredicates to specify the index column. This method is equivalent to "INDEXED BY" in the SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Name of the index column, which cannot be an empty string.

Return value

Type Description
RdbPredicates RdbPredicates object created.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.indexedBy("SALARY_INDEX")

[h2]in

in(field: string, value: Array<ValueType>): RdbPredicates

Creates an RdbPredicates object to search for the records in the specified column that are within the specified range.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
field string Yes Column name in the database table. It cannot be an empty string.
value Array<ValueType> Yes Array of ValueTypes to match.

Return value

Type Description
RdbPredicates Predicate that configures the condition that the value is within the given range.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.in("AGE", [18, 20])

[h2]notIn

notIn(field: string, value: Array<ValueType>): RdbPredicates

Creates an RdbPredicates object to search for the records in the specified column that are 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. It cannot be an empty string.
value Array<ValueType> Yes Array of ValueTypes to match.

Return value

Type Description
RdbPredicates Predicate configured with the condition that the value is out of the given range.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.notIn("NAME", ["Lisa", "Rose"])

RdbStore

Provides APIs for managing data in an RDB store.

Before using the APIs of this class, use executeSql to initialize the database table structure and related data.

[h2]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 specified target table. It cannot be an empty string.
values ValuesBucket Yes Row of data to insert.
callback AsyncCallback<number> Yes Callback function invoked to return the row ID. If the operation succeeds, err is undefined and data is the row ID; otherwise, data is an error object.

Example

import { ValuesBucket } from '@ohos.data.ValuesBucket';

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "CODES";
let value1 = "Lisi";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);
const valueBucket: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};

rdbStore.insert("EMPLOYEE", valueBucket, (status: number, rowId: number) => {
  if (status) {
    console.error("Insert failed");
    return;
  }
  console.info("Insert is successful, rowId = " + rowId);
})

[h2]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 specified target table. It cannot be an empty string.
values 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

import { ValuesBucket } from '@ohos.data.ValuesBucket';

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "CODES";
let value1 = "Lisi";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);
const valueBucket: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};

let promise: void = rdbStore.insert("EMPLOYEE", valueBucket)
promise.then((rowId: BusinessError) => {
  console.info("Insert is successful, rowId = " + rowId);
}).catch((status: number) => {
  console.error("Insert failed");
})

[h2]batchInsert

batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void

Inserts a batch 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 specified target table. It cannot be an empty string.
values Array<ValuesBucket> Yes An array of 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 inserted records; otherwise, err is an error object.

Example

import { ValuesBucket } from '@ohos.data.ValuesBucket';

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "CODES";
let value1 = "Lisa";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);
let value5 = "Jack";
let value6 = 19;
let value7 = 101.5;
let value8 = new Uint8Array([6, 7, 8, 9, 10]);
let value9 = "Tom";
let value10 = 20;
let value11 = 102.5;
let value12 = new Uint8Array([11, 12, 13, 14, 15]);
const valueBucket1: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};
const valueBucket2: ValuesBucket = {
  key1: value5,
  key2: value6,
  key3: value7,
  key4: value8,
};
const valueBucket3: ValuesBucket = {
  key1: value9,
  key2: value10,
  key3: value11,
  key4: value12,
};

let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3);
rdbStore.batchInsert("EMPLOYEE", valueBuckets, (status: number, insertNum: number) => {
  if (status) {
    console.error("batchInsert failed, status = " + status);
    return;
  }
  console.info("batchInsert is successful, the number of values that were inserted = " + insertNum);
})

[h2]batchInsert

batchInsert(table: string, values: Array<ValuesBucket>):Promise<number>

Inserts a batch 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 specified target table. It cannot be an empty string.
values Array<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

import { ValuesBucket } from '@ohos.data.ValuesBucket';

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "CODES";
let value1 = "Lisa";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);
let value5 = "Jack";
let value6 = 19;
let value7 = 101.5;
let value8 = new Uint8Array([6, 7, 8, 9, 10]);
let value9 = "Tom";
let value10 = 20;
let value11 = 102.5;
let value12 = new Uint8Array([11, 12, 13, 14, 15]);
const valueBucket1: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};
const valueBucket2: ValuesBucket = {
  key1: value5,
  key2: value6,
  key3: value7,
  key4: value8,
};
const valueBucket3: ValuesBucket = {
  key1: value9,
  key2: value10,
  key3: value11,
  key4: value12,
};

let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3);
let promise: void = rdbStore.batchInsert("EMPLOYEE", valueBuckets);
promise.then((insertNum: number) => {
  console.info("batchInsert is successful, the number of values that were inserted = " + insertNum);
}).catch((status: number) => {
  console.error("batchInsert failed, status = " + status);
})

[h2]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 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 Yes Update conditions specified by the RdbPredicates object.
callback AsyncCallback<number> Yes Callback function. If the operation is successful, err is undefined and data is the number of affected rows; otherwise, it is an error object.

Example

import { ValuesBucket } from '@ohos.data.ValuesBucket';

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "CODES";
let value1 = "Lisa";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);

const valueBucket: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};
let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa")
rdbStore.update(valueBucket, predicates, (err: BusinessError, rows: number) => {
  if (err) {
    console.error("Update failed, err: " + err)
    return
  }
  console.info("Updated row count: " + rows)
})

[h2]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 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 Yes Update conditions specified by the RdbPredicates object.

Return value

Type Description
Promise<number> Promise used to return the number of rows updated.

Example

import { ValuesBucket } from '@ohos.data.ValuesBucket';

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "CODES";
let value1 = "Lisa";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);

const valueBucket: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};
let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa")
let promise: void = rdbStore.update(valueBucket, predicates)
promise.then(async (rows: number) => {
  console.info("Updated row count: " + rows)
}).catch((err: BusinessError) => {
  console.error("Update failed, err: " + err)
})

[h2]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 Yes Deletion conditions specified by the RdbPredicates object.
callback AsyncCallback<number> Yes Callback function. If the operation is successful, err is undefined and data is the number of affected rows; otherwise, it is an error object.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa")
rdbStore.delete(predicates, (err: BusinessError, rows: number) => {
  if (err) {
    console.error("Delete failed, err: " + err)
    return
  }
  console.info("Delete rows: " + rows)
})

[h2]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 Yes Deletion conditions specified by the RdbPredicates object.

Return value

Type Description
Promise<number> Promise used to return the number of rows deleted.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Lisa")
let promise: void = rdbStore.delete(predicates)
promise.then((rows: number) => {
  console.info("Delete rows: " + rows)
}).catch((err: BusinessError) => {
  console.error("Delete failed, err: " + err)
})

[h2]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 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> Yes Callback used to return the result. If the query is successful, err is undefined and data is the obtained ResultSet object. Otherwise, err is an error object.
callback AsyncCallback<ResultSet> Yes Callback invoked to return the result. If the operation is successful, err is undefined and data is the ResultSet object; otherwise, data is an error object.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose")
rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], (err: BusinessError, resultSet: void) => {
  if (err) {
    console.error("Query failed, err: " + err)
    return
  }
  console.info("ResultSet column names: " + resultSet.columnNames)
  console.info("ResultSet column count: " + resultSet.columnCount)
})

[h2]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 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> Promise object. If the operation is successful, the ResultSet object is returned.

Example

let predicates = new data_rdb.RdbPredicates("EMPLOYEE")
predicates.equalTo("NAME", "Rose")
let promise: void = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"])
promise.then((resultSet: void) => {
  console.info("ResultSet column names: " + resultSet.columnNames)
  console.info("ResultSet column count: " + resultSet.columnCount)
}).catch((err: BusinessError) => {
  console.error("Query failed, err: " + err)
})

[h2]querySql8+

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 execute. It cannot be empty.
bindArgs Array<ValueType> Yes Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array.
callback AsyncCallback<ResultSet> Yes Callback used to return the result. If the query is successful, err is undefined and data is the obtained ResultSet object. Otherwise, err is an error object.
callback AsyncCallback<ResultSet> Yes Callback invoked to return the result. If the operation is successful, err is undefined and data is the ResultSet object; otherwise, data is an error object.

Example

rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], (err: BusinessError, resultSet: void) => {
  if (err) {
    console.error("Query failed, err: " + err)
    return
  }
  console.info("ResultSet column names: " + resultSet.columnNames)
  console.info("ResultSet column count: " + resultSet.columnCount)
})

[h2]querySql8+

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 execute. It cannot be empty.
bindArgs Array<ValueType> No Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.

Return value

Type Description
Promise<ResultSet> Promise object. If the operation is successful, the ResultSet object is returned.

Example

let promise: void = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'")
promise.then((resultSet: void) => {
  console.info("ResultSet column names: " + resultSet.columnNames)
  console.info("ResultSet column count: " + resultSet.columnCount)
}).catch((err: BusinessError) => {
  console.error("Query failed, err: " + err)
})

[h2]executeSql8+

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 execute. It cannot be empty.
bindArgs Array<ValueType> Yes Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array.
callback AsyncCallback<void> Yes Callback invoked when the operation succeeds, err is undefined; otherwise, it is an error object.

Example

const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = ?"
rdbStore.executeSql(SQL_DELETE_TABLE, ['zhangsan'], (err: BusinessError) => {
  if (err) {
    console.error("ExecuteSql failed, err: " + err)
    return
  }
  console.info('Delete table done.')
})

[h2]executeSql8+

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 execute. It cannot be empty.
bindArgs Array<ValueType> No Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.

Return value

Type Description
Promise<void> Promise that returns no value.

Example

const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'"
let promise = rdbStore.executeSql(SQL_DELETE_TABLE)
promise.then(() => {
  console.info('Delete table done.')
}).catch((err: BusinessError) => {
  console.error("ExecuteSql failed, err: " + err)
})

[h2]beginTransaction8+

beginTransaction():void

Starts the transaction before executing an SQL statement.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Example

import featureAbility from '@ohos.ability.featureAbility';
import { ValuesBucket } from '@ohos.data.ValuesBucket';

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "blobType";
let value1 = "Lisa";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3]);

const valueBucket: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};

data_rdb.getRdbStore(this.context, "RdbTest.db", 1, async (err: BusinessError, rdbStore) => {
  rdbStore.beginTransaction()
  await rdbStore.insert("test", valueBucket)
  rdbStore.commit()
})

[h2]commit8+

commit():void

Commits the executed SQL statements.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Example

import { ValuesBucket } from '@ohos.data.ValuesBucket';
import featureAbility from '@ohos.ability.featureAbility';

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "blobType";
let value1 = "Lisa";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3]);

const valueBucket: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};

data_rdb.getRdbStore(this.context, "RdbTest.db", 1, async (err: BusinessError, rdbStore) => {
  rdbStore.beginTransaction()
  await rdbStore.insert("test", valueBucket)
  rdbStore.commit()
})

[h2]rollBack8+

rollBack():void

Rolls back the SQL statements that have been executed.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Example

import { ValuesBucket } from '@ohos.data.ValuesBucket';
import featureAbility from '@ohos.ability.featureAbility';

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "blobType";
let value1 = "Lisa";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3]);

const valueBucket: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};

const STORE_CONFIG = { name: "RdbTest.db"}
data_rdb.getRdbStore(this,context, "RdbTest.db", 1, async (err: BusinessError, rdbStore) => {
  try {
    rdbStore.beginTransaction()
    await rdbStore.insert("test", valueBucket)
    rdbStore.commit()
  } catch (e) {
    rdbStore.rollBack()
  }
})

[h2]setDistributedTables8+

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 when the operation succeeds, err is undefined; otherwise, it is an error object.

Example

rdbStore.setDistributedTables(["EMPLOYEE"], (err: BusinessError) => {
  if (err) {
    console.error('SetDistributedTables failed, err: ' + err)
    return
  }
  console.info('SetDistributedTables successfully.')
})

[h2]setDistributedTables8+

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

let promise: void = rdbStore.setDistributedTables(["EMPLOYEE"])
promise.then(() => {
  console.info("SetDistributedTables successfully.")
}).catch((err: BusinessError) => {
  console.error("SetDistributedTables failed, err: " + err)
})

[h2]obtainDistributedTableName8+

obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void

Obtains the distributed table name of a remote device based on the local table name of the device. The distributed table name is required when the RDB store of a remote device is queried. This API uses an asynchronous callback to return the result.

The value of device can be obtained by deviceManager.getTrustedDeviceListSync. The APIs of the deviceManager module are system interfaces and available only to system applications.

Required permissions: ohos.permission.DISTRIBUTED_DATASYNC

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
device string Yes ID of the remote device.
table string Yes Local table name of the remote device.
callback AsyncCallback<string> Yes Callback function. When the operation succeeds, err is undefined and data is the distributed table name of the remote device; otherwise, it is an error object.

Example

import deviceManager from '@ohos.distributedHardware.deviceManager';

let dmInstance: Array<string>;

deviceManager.createDeviceManager("com.example.appdatamgrverify", (err: BusinessError, manager: void) => {
  if (err) {
    console.error("create device manager failed, err=" + err);
    return;
  }
  dmInstance = manager;
  let devices: Array<string> = dmInstance.getTrustedDeviceListSync();
  let deviceId: Array<string> = devices[0].deviceId;
})

rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE", (err: BusinessError, tableName: String) {
  if (err) {
    console.error('ObtainDistributedTableName failed, err: ' + err)
    return
  }
  console.info('ObtainDistributedTableName successfully, tableName=.' + tableName)
})

[h2]obtainDistributedTableName8+

obtainDistributedTableName(device: string, table: string): Promise<string>

Obtains the distributed table name of a remote device based on the local table name of the device. The distributed table name is required when the RDB store of a remote device is queried. This API uses a promise to return the result.

The value of device can be obtained by deviceManager.getTrustedDeviceListSync. The APIs of the deviceManager module are system interfaces and available only to system applications.

Required permissions: ohos.permission.DISTRIBUTED_DATASYNC

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
device string Yes ID of the remote device.
table string Yes Local table name of the remote device.

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

import deviceManager from '@ohos.distributedHardware.deviceManager';

let dmInstance: Array<string>;

deviceManager.createDeviceManager("com.example.appdatamgrverify", (err: BusinessError, manager: void) => {
  if (err) {
    console.error("create device manager failed, err=" + err);
    return;
  }
  dmInstance = manager;
  let devices: Array<string> = dmInstance.getTrustedDeviceListSync();
  let deviceId: Array<string> = devices[0].deviceId;
})

let promise: void = rdbStore.obtainDistributedTableName(deviceId, "EMPLOYEE")
promise.then((tableName: String) => {
  console.info('ObtainDistributedTableName successfully, tableName= ' + tableName)
}).catch((err: BusinessError) => {
  console.error('ObtainDistributedTableName failed, err: ' + err)
})

[h2]sync8+

sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback<Array<[string, number]>>): void

Synchronizes data across 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 Yes Data sync mode. The value can be push or pull.
predicates RdbPredicates Yes RdbPredicates object that specifies the data and devices to synchronize.
callback AsyncCallback<Array<[string, number]>> Yes Callback function. If the operation is successful, err is undefined and data is the synchronization result, where string is the device ID and number is the synchronization status of each device, with 0 indicating success and other values indicating failure; otherwise, it is an error object.

Example

import deviceManager from '@ohos.distributedHardware.deviceManager';

let dmInstance: Array<string>;

deviceManager.createDeviceManager("com.example.appdatamgrverify", (err: BusinessError, manager: void) => {
  if (err) {
    console.error("create device manager failed, err=" + err);
    return;
  }
  dmInstance = manager;
  let devices: Array<string> = dmInstance.getTrustedDeviceListSync();
  for (let i = 0; i < devices.length; i++) {
    let deviceIds: Array<string> = devices[i].deviceId;
  }
})

let predicates = new data_rdb.RdbPredicates('EMPLOYEE')
predicates.inDevices(deviceIds)
rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, (err: BusinessError, result: void) {
  if (err) {
    console.error('Sync failed, err: ' + err)
    return
  }
  console.info('Sync done.')
  for (let i = 0; i < result.length; i++) {
    console.info('device=' + result[i][0] + ' status=' + result[i][1])
  }
})

[h2]sync8+

sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>>

Synchronizes data across 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 Yes Data sync mode. The value can be push or pull.
predicates 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 sync result.

string indicates the device ID.

number indicates the sync status of that device. The value 0 indicates a successful sync. Other values indicate a sync failure.

Example

import deviceManager from '@ohos.distributedHardware.deviceManager';

let dmInstance: Array<string>;

deviceManager.createDeviceManager("com.example.appdatamgrverify", (err: BusinessError, manager: void) => {
  if (err) {
    console.error("create device manager failed, err=" + err);
    return;
  }
  dmInstance = manager;
  let devices: Array<string> = dmInstance.getTrustedDeviceListSync();
  for (let i = 0; i < devices.length; i++) {
    let deviceIds: Array<string> = devices[i].deviceId;
  }
})

let predicates = new data_rdb.RdbPredicates('EMPLOYEE')
predicates.inDevices(deviceIds)
let promise: void = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates)
promise.then((result: void) =>{
  console.info('Sync done.')
  for (let i = 0; i < result.length; i++) {
    console.info('device=' + result[i][0] + ' status=' + result[i][1])
  }
}).catch((err: BusinessError) => {
  console.error('Sync failed')
})

[h2]on('dataChange')8+

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 Event to observe. The value is dataChange, which indicates a data change event.
type SubscribeType Yes Subscription type to register.
observer Callback<Array<string>> Yes Observer that listens for the data changes in the RDB store. Array<string> indicates the ID of the peer device whose data in the database is changed.

Example

let devices: Array<string>;

try {
  rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver: Array<string>) => {
    for (let i = 0; i < devices.length; i++) {
      console.info('device=' + devices[i] + ' data changed')
    }
  })
} catch (err) {
  console.error('Register observer failed')
}

[h2]off('dataChange')8+

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 Event to observe. The value is dataChange, which indicates a data change event.
type SubscribeType Yes Subscription type to register.
observer Callback<Array<string>> Yes Data change observer registered. Array<string> indicates the ID of the peer device whose data in the database is changed.

Example

let devices: Array<string>;

try {
  rdbStore.off('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, (storeObserver: Array<string>) => {
    for (let i = 0; i < devices.length; i++) {
      console.info('device=' + devices[i] + ' data changed')
    }
  })
} catch (err) {
  console.error('Unregister observer failed')
}