8aad744f创建于 2025年7月21日历史提交

@ohos.data.relationalStore (关系型数据库)

关系型数据库(Relational Database,RDB)是一种基于关系模型来管理数据的数据库。关系型数据库基于SQLite组件提供了一套完整的对本地数据库进行管理的机制,对外提供了一系列的增、删、改、查等接口,也可以直接运行用户输入的SQL语句来满足复杂的场景需要。不支持Worker线程。

该模块提供以下关系型数据库相关的常用功能:

  • RdbPredicates: 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。
  • RdbStore:提供管理关系数据库(RDB)方法的接口。
  • ResultSet:提供用户调用关系型数据库查询接口之后返回的结果集合。

说明:

本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。

导入模块

import relationalStore from '@ohos.data.relationalStore'

relationalStore.getRdbStore

getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void

获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
context Context 应用的上下文。
Stage模型的应用Context定义见Context
config StoreConfig 与此RDB存储相关的数据库配置。
callback AsyncCallback<RdbStore> 指定callback回调函数,返回RdbStore对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800010 Failed to open or delete database by invalid database path.
14800011 Failed to open database by database corrupted.
14800000 Inner error.

Stage模型示例:

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

let store: relationalStore.RdbStore | undefined = undefined;

class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage) {
    const STORE_CONFIG: relationalStore.StoreConfig = {
      name: "RdbTest.db",
      securityLevel: relationalStore.SecurityLevel.S1
    };
        
    relationalStore.getRdbStore(this.context, STORE_CONFIG, (err: BusinessError, rdbStore: relationalStore.RdbStore) => {
      store = rdbStore;
      if (err) {
        console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`);
        return;
      }
      console.info(`Get RdbStore successfully.`);
    })
  }
}

relationalStore.getRdbStore

getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore>

获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
context Context 应用的上下文。
Stage模型的应用Context定义见Context
config StoreConfig 与此RDB存储相关的数据库配置。

返回值

类型 说明
Promise<RdbStore> Promise对象。返回RdbStore对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800010 Failed to open or delete database by invalid database path.
14800011 Failed to open database by database corrupted.
14800000 Inner error.

Stage模型示例:

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

let store: relationalStore.RdbStore | undefined = undefined;

class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage) {
    const STORE_CONFIG: relationalStore.StoreConfig = {
      name: "RdbTest.db",
      securityLevel: relationalStore.SecurityLevel.S1
    };

    relationalStore.getRdbStore(this.context, STORE_CONFIG).then(async (rdbStore: relationalStore.RdbStore) => {
      store = rdbStore;
      console.info(`Get RdbStore successfully.`)
    }).catch((err: BusinessError) => {
      console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`);
    })
  }
}

relationalStore.deleteRdbStore

deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void

删除数据库,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
context Context 应用的上下文。
Stage模型的应用Context定义见Context
name string 数据库名称。
callback AsyncCallback<void> 指定callback回调函数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800010 Failed to open or delete database by invalid database path.
14800000 Inner error.

Stage模型示例:

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

let store: relationalStore.RdbStore | undefined = undefined;

class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage){
    relationalStore.deleteRdbStore(this.context, "RdbTest.db", (err: BusinessError) => {
      if (err) {
        console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
        return;
      }
      store = undefined;
      console.info(`Delete RdbStore successfully.`);
    })
  }
}

relationalStore.deleteRdbStore

deleteRdbStore(context: Context, name: string): Promise<void>

使用指定的数据库文件配置删除数据库,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数

参数名 类型 必填 说明
context Context 应用的上下文。
Stage模型的应用Context定义见Context
name string 数据库名称。

返回值

类型 说明
Promise<void> 无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800010 Failed to open or delete database by invalid database path.
14800000 Inner error.

Stage模型示例:

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

let store: relationalStore.RdbStore | undefined = undefined;

class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage){
    relationalStore.deleteRdbStore(this.context, "RdbTest.db").then(()=>{
      store = undefined;
      console.info(`Delete RdbStore successfully.`);
    }).catch((err: BusinessError) => {
      console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
    })
  }
}

relationalStore.deleteRdbStore10+

deleteRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<void>): void

使用指定的数据库文件配置删除数据库,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
context Context 应用的上下文。
Stage模型的应用Context定义见Context
config StoreConfig 与此RDB存储相关的数据库配置。
callback AsyncCallback<void> 指定callback回调函数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800010 Failed to open or delete database by invalid database path.
14800000 Inner error.
14801001 Only supported in stage mode.
14801002 The data group id is not valid.

Stage模型示例:

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

let store: relationalStore.RdbStore | undefined = undefined;

class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage){
    const STORE_CONFIG: relationalStore.StoreConfig = {
      name: "RdbTest.db",
      securityLevel: relationalStore.SecurityLevel.S1
    };
    relationalStore.deleteRdbStore(this.context, STORE_CONFIG, (err: BusinessError) => {
      if (err) {
        console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
        return;
      }
      store = undefined;
      console.info(`Delete RdbStore successfully.`);
    })
  }
}

relationalStore.deleteRdbStore10+

deleteRdbStore(context: Context, config: StoreConfig): Promise<void>

使用指定的数据库文件配置删除数据库,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数

参数名 类型 必填 说明
context Context 应用的上下文。
Stage模型的应用Context定义见Context
config StoreConfig 与此RDB存储相关的数据库配置。

返回值

类型 说明
Promise<void> 无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800010 Failed to open or delete database by invalid database path.
14800000 Inner error.
14801001 Only supported in stage mode.
14801002 The data group id is not valid.

Stage模型示例:

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

let store: relationalStore.RdbStore | undefined = undefined;

class EntryAbility extends UIAbility {
  onWindowStageCreate(windowStage: window.WindowStage){
    const STORE_CONFIG: relationalStore.StoreConfig = {
      name: "RdbTest.db",
      securityLevel: relationalStore.SecurityLevel.S1
    };
    relationalStore.deleteRdbStore(this.context, STORE_CONFIG).then(()=>{
      store = undefined;
      console.info(`Delete RdbStore successfully.`);
    }).catch((err: BusinessError) => {
      console.error(`Delete RdbStore failed, code is ${err.code},message is ${err.message}`);
    })
  }
}

StoreConfig

管理关系数据库配置。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 类型 必填 说明
name string 数据库文件名。
securityLevel SecurityLevel 设置数据库安全级别
encrypt boolean 指定数据库是否加密,默认不加密。
true:加密。
false:非加密。
如该参数指定为true,需同时配置cryptoParam参数,配置加密数据库密钥。
dataGroupId10+ string 应用组ID,需要向应用市场获取。
模型约束: 此属性仅在Stage模型下可用。
从API version 10开始,支持此可选参数。指定在此dataGroupId对应的沙箱路径下创建RdbStore实例,当此参数不填时,默认在本应用沙箱目录下创建RdbStore实例。
customDir11+ string 数据库自定义路径。
使用约束: 数据库路径大小限制为128字节,如果超过该大小会开库失败,返回错误。
从API version 11开始,支持此可选参数。数据库将在如下的目录结构中被创建:context.databaseDir + "/rdb/" + customDir,其中context.databaseDir是应用沙箱对应的路径,"/rdb/"表示创建的是关系型数据库,customDir表示自定义的路径。当此参数不填时,默认在本应用沙箱目录下创建RdbStore实例。
isReadOnly20+ boolean 指定数据库是否只读,默认为数据库可读写。
true:只允许从数据库读取数据,不允许对数据库进行写操作,否则会返回错误码801。
false:允许对数据库进行读写操作。
从API version 12开始,支持此可选参数。
系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core
rootDir20+ string 指定数据库根路径。
从API version 18开始,支持此可选参数。将从如下目录打开或删除数据库:rootDir + "/" + customDir。通过设置此参数打开的数据库为只读模式,不允许对数据库进行写操作,否则返回错误码801。配置此参数打开或删除数据库时,应确保对应路径下数据库文件存在,并且有读取权限,否则返回错误码14800010。
系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core
cryptoParam20+ CryptoParam 指定用户自定义的加密参数。
当此参数不填时,使用默认的加密参数,见CryptoParam各参数默认值。
此配置只有在encrypt选项设置为真时才有效。
从API version 14开始,支持此可选参数。
系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core
persist20+ boolean 指定数据库是否需要持久化。true表示持久化,false表示不持久化,即内存数据库。默认为true。
内存数据库不支持加密、backup、restore、跨进程访问及分布式能力,securityLevel属性会被忽略。
系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

SecurityLevel

数据库的安全级别枚举。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 说明
S1 1 表示数据库的安全级别为低级别,当数据泄露时会产生较低影响。例如,包含壁纸等系统数据的数据库。
S2 2 表示数据库的安全级别为中级别,当数据泄露时会产生较大影响。例如,包含录音、视频等用户生成数据或通话记录等信息的数据库。
S3 3 表示数据库的安全级别为高级别,当数据泄露时会产生重大影响。例如,包含用户运动、健康、位置等信息的数据库。
S4 4 表示数据库的安全级别为关键级别,当数据泄露时会产生严重影响。例如,包含认证凭据、财务数据等信息的数据库。

CryptoParam20+

数据库加密参数配置。此配置只有在StoreConfig的encrypt选项设置为true时有效。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 类型 必填 说明
encryptionKey Uint8Array 指定数据库加/解密使用的密钥。
使用完后用户需要将密钥内容全部置为零。
iterationCount number 整数类型,指定数据库PBKDF2算法的迭代次数,默认值为10000。
迭代次数应当为大于零的整数,若非整数则向下取整。
不指定此参数或指定为零时,使用默认值10000,并使用默认加密算法AES_256_GCM。
encryptionAlgo EncryptionAlgo 指定数据库加解密使用的加密算法。如不指定,默认值为 AES_256_GCM。
hmacAlgo HmacAlgo 指定数据库加解密使用的HMAC算法。如不指定,默认值为SHA256。
kdfAlgo KdfAlgo 指定数据库加解密使用的PBKDF2算法。如不指定,默认使用和HMAC算法相等的算法。
cryptoPageSize number 整数类型,指定数据库加解密使用的页大小。如不指定,默认值为1024字节。
用户指定的页大小应为1024到65536范围内的整数,并且为2n。若指定值非整数,则向下取整。

HmacAlgo20+

数据库的HMAC算法枚举。请使用枚举名称而非枚举值。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 说明
SHA1 0 HMAC_SHA1算法。
SHA256 1 HMAC_SHA256算法。
SHA512 2 HMAC_SHA512算法。

KdfAlgo20+

数据库的PBKDF2算法枚举。请使用枚举名称而非枚举值。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 说明
KDF_SHA1 0 PBKDF2_HMAC_SHA1算法。
KDF_SHA256 1 PBKDF2_HMAC_SHA256算法。
KDF_SHA512 2 PBKDF2_HMAC_SHA512算法。

Field20+

用于谓词查询条件的特殊字段。请使用枚举名称而非枚举值。

系统能力: SystemCapability.DistributedDataManager.CloudSync.Client

名称 说明
CURSOR_FIELD '#_cursor' 用于cursor查找的字段名。
ORIGIN_FIELD '#_origin' 用于cursor查找时指定数据来源的字段名。
DELETED_FLAG_FIELD '#_deleted_flag' 用于cursor查找的结果集返回时填充的字段,表示云端删除的数据同步到本地后数据是否清理。
返回的结果集中,该字段对应的value为false表示数据未清理,true表示数据已清理。
DATA_STATUS_FIELD12+ '#_data_status' 用于cursor查找的结果集返回时填充的字段,返回的结果集中,该字段对应的0表示正常数据,1表示退出账号保留数据,2表示云侧同步删除,3表示退出账户删除数据。
OWNER_FIELD '#_cloud_owner' 用于共享表中查找owner时,返回的结果集中填充的字段,表示当前共享记录的共享发起者。
PRIVILEGE_FIELD '#_cloud_privilege' 用于共享表中查找共享数据权限时,返回的结果集中填充的字段,表示当前共享记录的允许的操作权限。
SHARING_RESOURCE_FIELD '#_sharing_resource_field' 用于数据共享查找共享数据的共享资源时,返回的结果集中填充的字段,表示共享数据的共享资源标识。

AssetStatus10+

描述资产附件的状态枚举。请使用枚举名称而非枚举值。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 说明
ASSET_NORMAL - 表示资产状态正常。
ASSET_INSERT - 表示资产需要插入到云端。
ASSET_UPDATE - 表示资产需要更新到云端。
ASSET_DELETE - 表示资产需要在云端删除。
ASSET_ABNORMAL - 表示资产状态异常。
ASSET_DOWNLOADING - 表示资产正在下载到本地设备。

Asset10+

记录资产附件(文件、图片、视频等类型文件)的相关信息。资产类型的相关接口暂不支持Datashare。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 类型 必填 说明
name string 资产的名称。
uri string 资产的uri,在系统里的绝对路径。
path string 资产在应用沙箱里的路径。
createTime string 资产被创建出来的时间。
modifyTime string 资产最后一次被修改的时间。
size string 资产占用空间的大小。
status AssetStatus 资产的状态,默认值为ASSET_NORMAL。

Assets10+

表示Asset类型的数组。

类型 说明
Asset[] 表示Asset类型的数组。

ValueType

用于表示允许的数据字段类型。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

类型 说明
null10+ 表示值类型为空。
number 表示值类型为数字。
string 表示值类型为字符。
boolean 表示值类型为布尔值。
Uint8Array10+ 表示值类型为Uint8类型的数组。
Asset10+ 表示值类型为附件Asset
Assets10+ 表示值类型为附件数组Assets

ValuesBucket

用于存储键值对的类型。该类型不是多线程安全的,如果应用中存在多线程同时操作该类派生出的实例,注意加锁保护。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

键类型 值类型
string ValueType

SqlExecutionInfo20+

描述数据库执行的SQL语句的统计信息。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 类型 只读 可选 说明
sql12+ Array<string> 表示执行的SQL语句的数组。当batchInsert的参数太大时,可能有多个SQL。
totalTime12+ number 表示执行SQL语句的总时间,单位为μs。
waitTime12+ number 表示获取句柄的时间,单位为μs。
prepareTime12+ number 表示准备SQL和绑定参数的时间,单位为μs。
executeTime12+ number 表示执行SQL语句的时间,单位为μs。

TransactionType20+

描述创建事务对象的枚举。请使用枚举名称而非枚举值。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 说明
DEFERRED 0 表示创建一个DEFERRED类型的事务对象,该类型的事务对象在创建时只会关闭自动提交而不会真正开始事务,只有在首次读或写操作时会真正开始一个读或写事务。
IMMEDIATE 1 表示创建一个IMMEDIATE类型的事务对象,该类型的事务对象在创建时会真正开始一个写事务;如果有别的写事务未提交,则会创建失败,返回错误码14800024。
EXCLUSIVE 2 表示创建一个EXCLUSIVE类型的事务对象,该类型的事务在WAL模式下和IMMEDIATE相同,但在其他日志模式下能够防止事务期间有其他连接读取数据库。

TransactionOptions20+

事务对象的配置信息。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 类型 必填 说明
transactionType TransactionType 事务类型。默认为DEFERRED。

ConflictResolution10+

插入和修改接口的冲突解决方式。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 说明
ON_CONFLICT_NONE 0 表示当冲突发生时,不做任何处理。
ON_CONFLICT_ROLLBACK 1 表示当冲突发生时,中止SQL语句并回滚当前事务。
ON_CONFLICT_ABORT 2 表示当冲突发生时,中止当前SQL语句,并撤销当前 SQL 语句所做的任何更改,但是由同一事务中先前的 SQL 语句引起的更改被保留并且事务保持活动状态。
ON_CONFLICT_FAIL 3 表示当冲突发生时,中止当前 SQL 语句。但它不会撤销失败的 SQL 语句的先前更改,也不会结束事务。
ON_CONFLICT_IGNORE 4 表示当冲突发生时,跳过包含违反约束的行并继续处理 SQL 语句的后续行。
ON_CONFLICT_REPLACE 5 表示当冲突发生时,在插入或更新当前行之前删除导致约束违例的预先存在的行,并且命令会继续正常执行。

RdbPredicates

表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。该类型不是多线程安全的,如果应用中存在多线程同时操作该类派生出的实例,注意加锁保护。

constructor

constructor(name: string)

构造函数。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
name string 数据库表名。

示例:

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");

equalTo

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

配置谓词以匹配数据字段为ValueType且值等于指定值的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value ValueType 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

notEqualTo

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

配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value ValueType 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

beginWrap

beginWrap(): RdbPredicates

向谓词添加左括号。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值

类型 说明
RdbPredicates 返回带有左括号的Rdb谓词。

示例:

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

endWrap

endWrap(): RdbPredicates

向谓词添加右括号。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值

类型 说明
RdbPredicates 返回带有右括号的Rdb谓词。

示例:

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

or

or(): RdbPredicates

将或条件添加到谓词中。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值

类型 说明
RdbPredicates 返回带有或条件的Rdb谓词。

示例:

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

and

and(): RdbPredicates

向谓词添加和条件。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值

类型 说明
RdbPredicates 返回带有和条件的Rdb谓词。

示例:

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

contains

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

配置谓词以匹配数据字段为string且value包含指定值的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value string 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

beginsWith

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

配置谓词以匹配数据字段为string且值以指定字符串开头的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value string 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

endsWith

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

配置谓词以匹配数据字段为string且值以指定字符串结尾的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value string 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

isNull

isNull(field: string): RdbPredicates

配置谓词以匹配值为null的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例

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

isNotNull

isNotNull(field: string): RdbPredicates

配置谓词以匹配值不为null的指定字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

like

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

配置谓词以匹配数据字段为string且值类似于指定字符串的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value string 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

glob

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

配置RdbPredicates匹配数据字段为string的指定字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value string 指示要与谓词匹配的值。
支持通配符,*表示0个、1个或多个数字或字符,?表示1个数字或字符。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

between

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

将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
low ValueType 指示与谓词匹配的最小值。
high ValueType 指示要与谓词匹配的最大值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

notBetween

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

配置RdbPredicates以匹配数据字段为ValueType且value超出给定范围的指定字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
low ValueType 指示与谓词匹配的最小值。
high ValueType 指示要与谓词匹配的最大值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

greaterThan

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

配置谓词以匹配数据字段为ValueType且值大于指定值的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value ValueType 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

lessThan

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

配置谓词以匹配数据字段为valueType且value小于指定值的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value ValueType 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

greaterThanOrEqualTo

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

配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value ValueType 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

lessThanOrEqualTo

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

配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value ValueType 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

orderByAsc

orderByAsc(field: string): RdbPredicates

配置谓词以匹配其值按升序排序的列。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

orderByDesc

orderByDesc(field: string): RdbPredicates

配置谓词以匹配其值按降序排序的列。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

distinct

distinct(): RdbPredicates

配置谓词以过滤重复记录并仅保留其中一个。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值

类型 说明
RdbPredicates 返回可用于过滤重复记录的谓词。

示例:

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

limitAs

limitAs(value: number): RdbPredicates

设置最大数据记录数的谓词。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
value number 最大数据记录数。

返回值

类型 说明
RdbPredicates 返回可用于设置最大数据记录数的谓词。

示例:

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

offsetAs

offsetAs(rowOffset: number): RdbPredicates

配置RdbPredicates以指定返回结果的起始位置。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
rowOffset number 返回结果的起始位置,取值为正整数。

返回值

类型 说明
RdbPredicates 返回具有指定返回结果起始位置的谓词。

示例:

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose").offsetAs(3);

groupBy

groupBy(fields: Array<string>): RdbPredicates

配置RdbPredicates按指定列分组查询结果。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
fields Array<string> 指定分组依赖的列名。

返回值

类型 说明
RdbPredicates 返回分组查询列的谓词。

示例:

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

indexedBy

indexedBy(field: string): RdbPredicates

配置RdbPredicates以指定索引列。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 索引列的名称。

返回值

类型 说明
RdbPredicates 返回具有指定索引列的RdbPredicates。

示例:

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

in

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

配置RdbPredicates以匹配数据字段为ValueType数组且值在给定范围内的指定字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value Array<ValueType> 以ValueType型数组形式指定的要匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

notIn

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

将RdbPredicates配置为匹配数据字段为ValueType且值超出给定范围的指定字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value Array<ValueType> 以ValueType数组形式指定的要匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

示例:

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

notContains20+

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

配置谓词以匹配数据表的field列中不包含value的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value string 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.

示例:

// 匹配数据表的"NAME"列中不包含"os"的字段,如列表中的"Lisa"
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.notContains("NAME", "os");

notLike20+

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

配置谓词以匹配数据表的field列中值不存在类似于value的字段。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
field string 数据库表中的列名。
value string 指示要与谓词匹配的值。

返回值

类型 说明
RdbPredicates 返回与指定字段匹配的谓词。

错误码:

以下错误码的详细介绍请参见通用错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.

示例:

// 匹配数据表的"NAME"列中不等于"os"的字段,如列表中的"Rose"
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.notLike("NAME", "os");

RdbStore

提供管理关系数据库(RDB)方法的接口。

在使用以下相关接口前,请使用executeSql接口初始化数据库表结构和相关数据。

属性10+

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 类型 必填 说明
version10+ number 设置和获取数据库版本,值为大于0的正整数。

示例:

// 设置数据库版本
if(store != undefined) {
  (store as relationalStore.RdbStore).version = 3;
  // 获取数据库版本
  console.info(`RdbStore version is ${store.version}`);
}

insert

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

向目标表中插入一行数据,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
table string 指定的目标表名。
values ValuesBucket 表示要插入到表中的数据行。
callback AsyncCallback<number> 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

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,
};
if(store != undefined) {
  (store as relationalStore.RdbStore).insert("EMPLOYEE", valueBucket, (err: BusinessError, rowId: number) => {
    if (err) {
      console.error(`Insert is failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`Insert is successful, rowId = ${rowId}`);
  })
}

insert10+

insert(table: string, values: ValuesBucket, conflict: ConflictResolution, callback: AsyncCallback<number>):void

向目标表中插入一行数据,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
table string 指定的目标表名。
values ValuesBucket 表示要插入到表中的数据行。
conflict ConflictResolution 指定冲突解决方式。
callback AsyncCallback<number> 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

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,
};
if(store != undefined) {
  (store as relationalStore.RdbStore).insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE,
    (err: BusinessError, rowId: number) => {
      if (err) {
        console.error(`Insert is failed, code is ${err.code},message is ${err.message}`);
        return;
      }
      console.info(`Insert is successful, rowId = ${rowId}`);
  })
}

insert

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

向目标表中插入一行数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
table string 指定的目标表名。
values ValuesBucket 表示要插入到表中的数据行。

返回值

类型 说明
Promise<number> Promise对象。如果操作成功,返回行ID;否则返回-1。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

import { ValuesBucket } from '@ohos.data.ValuesBucket';
import { BusinessError } from "@ohos.base";

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,
};
if(store != undefined) {
  (store as relationalStore.RdbStore).insert("EMPLOYEE", valueBucket).then((rowId: number) => {
    console.info(`Insert is successful, rowId = ${rowId}`);
  }).catch((err: BusinessError) => {
    console.error(`Insert is failed, code is ${err.code},message is ${err.message}`);
  })
}

insert10+

insert(table: string, values: ValuesBucket, conflict: ConflictResolution):Promise<number>

向目标表中插入一行数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
table string 指定的目标表名。
values ValuesBucket 表示要插入到表中的数据行。
conflict ConflictResolution 指定冲突解决方式。

返回值

类型 说明
Promise<number> Promise对象。如果操作成功,返回行ID;否则返回-1。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

import { ValuesBucket } from '@ohos.data.ValuesBucket';
import { BusinessError } from "@ohos.base";

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,
};
if(store != undefined) {
  (store as relationalStore.RdbStore).insert("EMPLOYEE", valueBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then((rowId: number) => {
    console.info(`Insert is successful, rowId = ${rowId}`);
  }).catch((err: BusinessError) => {
    console.error(`Insert is failed, code is ${err.code},message is ${err.message}`);
  })
}

batchInsert

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

向目标表中插入一组数据,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
table string 指定的目标表名。
values Array<ValuesBucket> 表示要插入到表中的一组数据。
callback AsyncCallback<number> 指定callback回调函数。如果操作成功,返回插入的数据个数,否则返回-1。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

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);
if(store != undefined) {
  (store as relationalStore.RdbStore).batchInsert("EMPLOYEE", valueBuckets, (err, insertNum) => {
    if (err) {
      console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
  })
}

batchInsert

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

向目标表中插入一组数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
table string 指定的目标表名。
values Array<ValuesBucket> 表示要插入到表中的一组数据。

返回值

类型 说明
Promise<number> Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

import { ValuesBucket } from '@ohos.data.ValuesBucket';
import { BusinessError } from "@ohos.base";

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);
if(store != undefined) {
  (store as relationalStore.RdbStore).batchInsert("EMPLOYEE", valueBuckets).then((insertNum: number) => {
    console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
  }).catch((err: BusinessError) => {
    console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`);
  })
}

createTransaction20+

createTransaction(options?: TransactionOptions): Promise<Transaction>

创建一个事务对象并开始事务,使用Promise异步回调。

beginTransaction的区别在于:createTransaction接口会返回一个事务对象,不同事务对象之间是隔离的。使用事务对象进行插入、删除或更新数据等操作,无法被注册数据变更通知on('dataChange')监听到。

一个store最多支持同时存在四个事务对象,超过后会返回14800015错误码,此时需要检查是否持有事务对象时间过长或并发事务过多,若确认无法通过上述优化解决问题,建议等待现有事务释放后,再尝试新建事务对象。

优先使用createTransaction,不再推荐使用beginTransaction。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
options TransactionOptions 表示事务对象的配置信息。

返回值

类型 说明
Promise<Transaction> Promise对象,返回事务对象。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800015 The database is busy.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800026 SQLite: The database is out of memory.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800030 SQLite: Unable to open the database file.

示例:

import { BusinessError } from '@kit.BasicServicesKit';

if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    transaction.execute("DELETE FROM test WHERE age = ? OR age = ?", [21, 20]).then(() => {
      transaction.commit();
    }).catch((e: BusinessError) => {
      transaction.rollback();
      console.error(`execute sql failed, code is ${e.code},message is ${e.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`createTransaction faided, code is ${err.code},message is ${err.message}`);
  });
}

update

update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void

根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
values ValuesBucket values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。
predicates RdbPredicates RdbPredicates的实例对象指定的更新条件。
callback AsyncCallback<number> 指定的callback回调方法。返回受影响的行数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

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

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "CODES";
let value1 = "Rose";
let value2 = 22;
let value3 = 200.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);
const valueBucket: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
if(store != undefined) {
  (store as relationalStore.RdbStore).update(valueBucket, predicates,(err, rows) => {
    if (err) {
      console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`Updated row count: ${rows}`);
  })
}

update10+

update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution, callback: AsyncCallback<number>):void

根据RdbPredicates的指定实例对象更新数据库中的数据,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
values ValuesBucket values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。
predicates RdbPredicates RdbPredicates的实例对象指定的更新条件。
conflict ConflictResolution 指定冲突解决方式。
callback AsyncCallback<number> 指定的callback回调方法。返回受影响的行数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

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

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "CODES";
let value1 = "Rose";
let value2 = 22;
let value3 = 200.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);
const valueBucket: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
if(store != undefined) {
  (store as relationalStore.RdbStore).update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE, (err, rows) => {
    if (err) {
      console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`Updated row count: ${rows}`);
  })
}

update

update(values: ValuesBucket, predicates: RdbPredicates):Promise<number>

根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
values ValuesBucket values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。
predicates RdbPredicates RdbPredicates的实例对象指定的更新条件。

返回值

类型 说明
Promise<number> 指定的Promise回调方法。返回受影响的行数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

import { ValuesBucket } from '@ohos.data.ValuesBucket';
import { BusinessError } from "@ohos.base";

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "CODES";
let value1 = "Rose";
let value2 = 22;
let value3 = 200.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);
const valueBucket: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
if(store != undefined) {
  (store as relationalStore.RdbStore).update(valueBucket, predicates).then(async (rows: Number) => {
    console.info(`Updated row count: ${rows}`);
  }).catch((err: BusinessError) => {
    console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
  })
}

update10+

update(values: ValuesBucket, predicates: RdbPredicates, conflict: ConflictResolution):Promise<number>

根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
values ValuesBucket values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。
predicates RdbPredicates RdbPredicates的实例对象指定的更新条件。
conflict ConflictResolution 指定冲突解决方式。

返回值

类型 说明
Promise<number> 指定的Promise回调方法。返回受影响的行数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

import { ValuesBucket } from '@ohos.data.ValuesBucket';
import { BusinessError } from "@ohos.base";

let key1 = "NAME";
let key2 = "AGE";
let key3 = "SALARY";
let key4 = "CODES";
let value1 = "Rose";
let value2 = 22;
let value3 = 200.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);
const valueBucket: ValuesBucket = {
  key1: value1,
  key2: value2,
  key3: value3,
  key4: value4,
};
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
if(store != undefined) {
  (store as relationalStore.RdbStore).update(valueBucket, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then(async (rows: Number) => {
    console.info(`Updated row count: ${rows}`);
  }).catch((err: BusinessError) => {
    console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
  })
}

delete

delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void

根据RdbPredicates的指定实例对象从数据库中删除数据,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
predicates RdbPredicates RdbPredicates的实例对象指定的删除条件。
callback AsyncCallback<number> 指定callback回调函数。返回受影响的行数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
if(store != undefined) {
  (store as relationalStore.RdbStore).delete(predicates, (err, rows) => {
    if (err) {
      console.error(`Delete failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`Delete rows: ${rows}`);
  })
}

delete

delete(predicates: RdbPredicates):Promise<number>

根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
predicates RdbPredicates RdbPredicates的实例对象指定的删除条件。

返回值

类型 说明
Promise<number> Promise对象。返回受影响的行数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

import { BusinessError } from "@ohos.base";

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");
if(store != undefined) {
  (store as relationalStore.RdbStore).delete(predicates).then((rows: Number) => {
    console.info(`Delete rows: ${rows}`);
  }).catch((err: BusinessError) => {
    console.error(`Delete failed, code is ${err.code},message is ${err.message}`);
  })
}

query10+

query(predicates: RdbPredicates, callback: AsyncCallback<ResultSet>):void

根据指定条件查询数据库中的数据,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
predicates RdbPredicates RdbPredicates的实例对象指定的查询条件。
callback AsyncCallback<ResultSet> 指定callback回调函数。如果操作成功,则返回ResultSet对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800000 Inner error.

示例:

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose");
if(store != undefined) {
  (store as relationalStore.RdbStore).query(predicates, (err, resultSet) => {
    if (err) {
      console.error(`Query failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
    // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
    while (resultSet.goToNextRow()) {
      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"));
      console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
    }
    // 释放数据集的内存
    resultSet.close();
  })
}

query

query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void

根据指定条件查询数据库中的数据,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
predicates RdbPredicates RdbPredicates的实例对象指定的查询条件。
columns Array<string> 表示要查询的列。如果值为空,则查询应用于所有列。
callback AsyncCallback<ResultSet> 指定callback回调函数。如果操作成功,则返回ResultSet对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800000 Inner error.

示例:

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose");
if(store != undefined) {
  (store as relationalStore.RdbStore).query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], (err, resultSet) => {
    if (err) {
      console.error(`Query failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
    // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
    while (resultSet.goToNextRow()) {
      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"));
      console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
    }
    // 释放数据集的内存
    resultSet.close();
  })
}

query

query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet>

根据指定条件查询数据库中的数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
predicates RdbPredicates RdbPredicates的实例对象指定的查询条件。
columns Array<string> 表示要查询的列。如果值为空,则查询应用于所有列。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800000 Inner error.

返回值

类型 说明
Promise<ResultSet> Promise对象。如果操作成功,则返回ResultSet对象。

示例:

import { BusinessError } from "@ohos.base";

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose");
if(store != undefined) {
  (store as relationalStore.RdbStore).query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet: relationalStore.ResultSet) => {
    console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
    // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
    while (resultSet.goToNextRow()) {
      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"));
      console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
    }
    // 释放数据集的内存
    resultSet.close();
  }).catch((err: BusinessError) => {
    console.error(`Query failed, code is ${err.code},message is ${err.message}`);
  })
}

querySql10+

querySql(sql: string, callback: AsyncCallback<ResultSet>):void

根据指定SQL语句查询数据库中的数据,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
sql string 指定要执行的SQL语句。
callback AsyncCallback<ResultSet> 指定callback回调函数。如果操作成功,则返回ResultSet对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800000 Inner error.

示例:

if(store != undefined) {
  (store as relationalStore.RdbStore).querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'", (err, resultSet) => {
    if (err) {
      console.error(`Query failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
    // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
    while (resultSet.goToNextRow()) {
      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"));
      console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
    }
    // 释放数据集的内存
    resultSet.close();
  })
}

querySql

querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void

根据指定SQL语句查询数据库中的数据,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
sql string 指定要执行的SQL语句。
bindArgs Array<ValueType> SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数需为空数组。
callback AsyncCallback<ResultSet> 指定callback回调函数。如果操作成功,则返回ResultSet对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800000 Inner error.

示例:

if(store != undefined) {
  (store as relationalStore.RdbStore).querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], (err, resultSet) => {
    if (err) {
      console.error(`Query failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
    // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
    while (resultSet.goToNextRow()) {
      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"));
      console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
    }
    // 释放数据集的内存
    resultSet.close();
  })
}

querySql

querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet>

根据指定SQL语句查询数据库中的数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
sql string 指定要执行的SQL语句。
bindArgs Array<ValueType> SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。

返回值

类型 说明
Promise<ResultSet> Promise对象。如果操作成功,则返回ResultSet对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800000 Inner error.

示例:

import { BusinessError } from "@ohos.base";

if(store != undefined) {
  (store as relationalStore.RdbStore).querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'").then((resultSet: relationalStore.ResultSet) => {
    console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
    // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
    while (resultSet.goToNextRow()) {
      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"));
      console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
    }
    // 释放数据集的内存
    resultSet.close();
  }).catch((err: BusinessError) => {
    console.error(`Query failed, code is ${err.code},message is ${err.message}`);
  })
}

executeSql10+

executeSql(sql: string, callback: AsyncCallback<void>):void

执行包含指定参数但不返回值的SQL语句,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
sql string 指定要执行的SQL语句。
callback AsyncCallback<void> 指定callback回调函数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'"
if(store != undefined) {
  (store as relationalStore.RdbStore).executeSql(SQL_DELETE_TABLE, (err) => {
    if (err) {
      console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`Delete table done.`);
  })
}

executeSql

executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void

执行包含指定参数但不返回值的SQL语句,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
sql string 指定要执行的SQL语句。
bindArgs Array<ValueType> SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数需为空数组。
callback AsyncCallback<void> 指定callback回调函数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = ?"
if(store != undefined) {
  (store as relationalStore.RdbStore).executeSql(SQL_DELETE_TABLE, ['zhangsan'], (err) => {
    if (err) {
      console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`Delete table done.`);
  })
}

executeSql

executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void>

执行包含指定参数但不返回值的SQL语句,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
sql string 指定要执行的SQL语句。
bindArgs Array<ValueType> SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。

返回值

类型 说明
Promise<void> 无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

import { BusinessError } from "@ohos.base";

const SQL_DELETE_TABLE = "DELETE FROM test WHERE name = 'zhangsan'"
if(store != undefined) {
  (store as relationalStore.RdbStore).executeSql(SQL_DELETE_TABLE).then(() => {
    console.info(`Delete table done.`);
  }).catch((err: BusinessError) => {
    console.error(`ExecuteSql failed, code is ${err.code},message is ${err.message}`);
  })
}

beginTransaction

beginTransaction():void

在开始执行SQL语句之前,开始事务。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800047 The WAL file size exceeds the default limit.
14800000 Inner error.

示例:

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

let context = getContext(this);

let key1 = "name";
let key2 = "age";
let key3 = "SALARY";
let key4 = "blobType";
let value1 = "Lisi";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3]);
const STORE_CONFIG: relationalStore.StoreConfig = {
  name: "RdbTest.db",
  securityLevel: relationalStore.SecurityLevel.S1
};
relationalStore.getRdbStore(context, STORE_CONFIG, async (err, store) => {
  if (err) {
    console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`);
    return;
  }
  store.beginTransaction();
  const valueBucket: ValuesBucket = {
    key1: value1,
    key2: value2,
    key3: value3,
    key4: value4,
  };
  await store.insert("test", valueBucket);
  store.commit();
})

commit

commit():void

提交已执行的SQL语句。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

示例:

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

let context = getContext(this);

let key1 = "name";
let key2 = "age";
let key3 = "SALARY";
let key4 = "blobType";
let value1 = "Lisi";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3]);
const STORE_CONFIG: relationalStore.StoreConfig = {
  name: "RdbTest.db",
  securityLevel: relationalStore.SecurityLevel.S1
};
relationalStore.getRdbStore(context, STORE_CONFIG, async (err, store) => {
  if (err) {
    console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`);
    return;
  }
  store.beginTransaction();
  const valueBucket: ValuesBucket = {
    key1: value1,
    key2: value2,
    key3: value3,
    key4: value4,
  };
  await store.insert("test", valueBucket);
  store.commit();
})

rollBack

rollBack():void

回滚已经执行的SQL语句。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

示例:

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

let context = getContext(this);

let key1 = "name";
let key2 = "age";
let key3 = "SALARY";
let key4 = "blobType";
let value1 = "Lisi";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3]);
const STORE_CONFIG: relationalStore.StoreConfig = {
  name: "RdbTest.db",
  securityLevel: relationalStore.SecurityLevel.S1
};
relationalStore.getRdbStore(context, STORE_CONFIG, async (err, store) => {
  if (err) {
    console.error(`GetRdbStore failed, code is ${err.code},message is ${err.message}`);
    return;
  }
  try {
    store.beginTransaction()
    const valueBucket: ValuesBucket = {
      key1: value1,
      key2: value2,
      key3: value3,
      key4: value4,
    };
    await store.insert("test", valueBucket);
    store.commit();
  } catch (err) {
    let code = (err as BusinessError).code;
    let message = (err as BusinessError).message
    console.error(`Transaction failed, code is ${code},message is ${message}`);
    store.rollBack();
  }
})

backup

backup(destName:string, callback: AsyncCallback<void>):void

以指定名称备份数据库,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
destName string 指定数据库的备份文件名。
callback AsyncCallback<void> 指定callback回调函数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800000 Inner error.

示例:

if(store != undefined) {
  (store as relationalStore.RdbStore).backup("dbBackup.db", (err) => {
    if (err) {
      console.error(`Backup failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`Backup success.`);
  })
}

backup

backup(destName:string): Promise<void>

以指定名称备份数据库,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
destName string 指定数据库的备份文件名。

返回值

类型 说明
Promise<void> 无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800000 Inner error.

示例:

import { BusinessError } from "@ohos.base";

if(store != undefined) {
  let promiseBackup = (store as relationalStore.RdbStore).backup("dbBackup.db");
  promiseBackup.then(() => {
    console.info(`Backup success.`);
  }).catch((err: BusinessError) => {
    console.error(`Backup failed, code is ${err.code},message is ${err.message}`);
  })
}

restore

restore(srcName:string, callback: AsyncCallback<void>):void

从指定的数据库备份文件恢复数据库,使用callback异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
srcName string 指定数据库的备份文件名。
callback AsyncCallback<void> 指定callback回调函数。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800000 Inner error.

示例:

if(store != undefined) {
  (store as relationalStore.RdbStore).restore("dbBackup.db", (err) => {
    if (err) {
      console.error(`Restore failed, code is ${err.code},message is ${err.message}`);
      return;
    }
    console.info(`Restore success.`);
  })
}

restore

restore(srcName:string): Promise<void>

从指定的数据库备份文件恢复数据库,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
srcName string 指定数据库的备份文件名。

返回值

类型 说明
Promise<void> 无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800000 Inner error.

示例:

import { BusinessError } from "@ohos.base";

if(store != undefined) {
  let promiseRestore = (store as relationalStore.RdbStore).restore("dbBackup.db");
  promiseRestore.then(() => {
    console.info(`Restore success.`);
  }).catch((err: BusinessError) => {
    console.error(`Restore failed, code is ${err.code},message is ${err.message}`);
  })
}

on('statistics')20+

on(event: 'statistics', observer: Callback<SqlExecutionInfo>): void

订阅SQL统计信息。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
event string 订阅事件名称,取值为'statistics',表示sql执行时间的统计。
observer Callback<SqlExecutionInfo> 回调函数。用于返回数据库中SQL执行时间的统计信息。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1.Mandatory parameters are left unspecified; 2.Incorrect parameter types.
801 Capability not supported.
14800000 Inner error.
14800014 The RdbStore or ResultSet is already closed.

示例:

import { BusinessError } from '@kit.BasicServicesKit';

let sqlExecutionInfo = (sqlExecutionInfo: relationalStore.SqlExecutionInfo) => {
  console.info(`sql: ${sqlExecutionInfo.sql[0]}`);
  console.info(`totalTime: ${sqlExecutionInfo.totalTime}`);
  console.info(`waitTime: ${sqlExecutionInfo.waitTime}`);
  console.info(`prepareTime: ${sqlExecutionInfo.prepareTime}`);
  console.info(`executeTime: ${sqlExecutionInfo.executeTime}`);
};

try {
  if (store != undefined) {
    (store as relationalStore.RdbStore).on('statistics', sqlExecutionInfo);
  }
} catch (err) {
  let code = (err as BusinessError).code;
  let message = (err as BusinessError).message;
  console.error(`Register observer failed, code is ${code},message is ${message}`);
}

try {
  let value1 = "Lisa";
  let value2 = 18;
  let value3 = 100.5;
  let value4 = new Uint8Array([1, 2, 3, 4, 5]);

  const valueBucket: relationalStore.ValuesBucket = {
    'NAME': value1,
    'AGE': value2,
    'SALARY': value3,
    'CODES': value4
  };
  if (store != undefined) {
    (store as relationalStore.RdbStore).insert('test', valueBucket);
  }
} catch (err) {
  console.error(`insert fail, code:${err.code}, message: ${err.message}`);
}

close20+

close(): Promise<void>

关闭数据库,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值:

类型 说明
Promise<void> Promise对象。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码

错误码ID 错误信息
401 Parameter error. The store must not be nullptr.
14800000 Inner error.

示例:

import { BusinessError } from '@kit.BasicServicesKit';

if (store != undefined) {
  (store as relationalStore.RdbStore).close().then(() => {
    console.info(`close succeeded`);
  }).catch((err: BusinessError) => {
    console.error(`close failed, code is ${err.code},message is ${err.message}`);
  });
}

ResultSet

提供通过查询数据库生成的数据库结果集的访问方法。结果集是指用户调用关系型数据库查询接口之后返回的结果集合,提供了多种灵活的数据访问方式,以便用户获取各项数据。

使用说明

首先需要获取resultSet对象。

let resultSet: relationalStore.ResultSet | undefined = undefined;
let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("AGE", 18);
if(store != undefined) {
  (store as relationalStore.RdbStore).query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((result: relationalStore.ResultSet) => {
    resultSet = result;
    console.info(`resultSet columnNames: ${resultSet.columnNames}`);
    console.info(`resultSet columnCount: ${resultSet.columnCount}`);
  });
}

属性

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

名称 类型 必填 说明
columnNames Array<string> 获取结果集中所有列的名称。
columnCount number 获取结果集中的列数。
rowCount number 获取结果集中的行数。
rowIndex number 获取结果集当前行的索引。
isAtFirstRow boolean 检查结果集是否位于第一行。
isAtLastRow boolean 检查结果集是否位于最后一行。
isEnded boolean 检查结果集是否位于最后一行之后。
isStarted boolean 检查指针是否移动过。
isClosed boolean 检查当前结果集是否关闭。

getColumnIndex

getColumnIndex(columnName: string): number

根据指定的列名获取列索引。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
columnName string 表示结果集中指定列的名称。

返回值:

类型 说明
number 返回指定列的索引。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800013 The column value is null or the column type is incompatible.

示例:

if(resultSet != undefined) {
  const id = (resultSet as relationalStore.ResultSet).getLong((resultSet as relationalStore.ResultSet).getColumnIndex("ID"));
  const name = (resultSet as relationalStore.ResultSet).getString((resultSet as relationalStore.ResultSet).getColumnIndex("NAME"));
  const age = (resultSet as relationalStore.ResultSet).getLong((resultSet as relationalStore.ResultSet).getColumnIndex("AGE"));
  const salary = (resultSet as relationalStore.ResultSet).getDouble((resultSet as relationalStore.ResultSet).getColumnIndex("SALARY"));
}

getColumnName

getColumnName(columnIndex: number): string

根据指定的列索引获取列名。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
columnIndex number 表示结果集中指定列的索引。

返回值:

类型 说明
string 返回指定列的名称。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800013 The column value is null or the column type is incompatible.

示例:

if(resultSet != undefined) {
const id = (resultSet as relationalStore.ResultSet).getColumnName(0);
const name = (resultSet as relationalStore.ResultSet).getColumnName(1);
const age = (resultSet as relationalStore.ResultSet).getColumnName(2);
}

goTo

goTo(offset:number): boolean

向前或向后转至结果集的指定行,相对于其当前位置偏移。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
offset number 表示相对于当前位置的偏移量。

返回值:

类型 说明
boolean 如果成功移动结果集,则为true;否则返回false。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800012 The result set is empty or the specified location is invalid.

示例:

if(resultSet != undefined) {
(resultSet as relationalStore.ResultSet).goTo(1);
}

goToRow

goToRow(position: number): boolean

转到结果集的指定行。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
position number 表示要移动到的指定位置。

返回值:

类型 说明
boolean 如果成功移动结果集,则为true;否则返回false。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800012 The result set is empty or the specified location is invalid.

示例:

if(resultSet != undefined) {
(resultSet as relationalStore.ResultSet).goToRow(5);
}

goToFirstRow

goToFirstRow(): boolean

转到结果集的第一行。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值:

类型 说明
boolean 如果成功移动结果集,则为true;否则返回false。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800012 The result set is empty or the specified location is invalid.

示例:

if(resultSet != undefined) {
(resultSet as relationalStore.ResultSet).goToFirstRow();
}

goToLastRow

goToLastRow(): boolean

转到结果集的最后一行。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值:

类型 说明
boolean 如果成功移动结果集,则为true;否则返回false。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800012 The result set is empty or the specified location is invalid.

示例:

if(resultSet != undefined) {
(resultSet as relationalStore.ResultSet).goToLastRow();
}

goToNextRow

goToNextRow(): boolean

转到结果集的下一行。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值:

类型 说明
boolean 如果成功移动结果集,则为true;否则返回false。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800012 The result set is empty or the specified location is invalid.

示例:

if(resultSet != undefined) {
(resultSet as relationalStore.ResultSet).goToNextRow();
}

goToPreviousRow

goToPreviousRow(): boolean

转到结果集的上一行。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值:

类型 说明
boolean 如果成功移动结果集,则为true;否则返回false。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800012 The result set is empty or the specified location is invalid.

示例:

if(resultSet != undefined) {
(resultSet as relationalStore.ResultSet).goToPreviousRow();
}

getBlob

getBlob(columnIndex: number): Uint8Array

以字节数组的形式获取当前行中指定列的值。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
columnIndex number 指定的列索引,从0开始。

返回值:

类型 说明
Uint8Array 以字节数组的形式返回指定列的值。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800013 The column value is null or the column type is incompatible.

示例:

if(resultSet != undefined) {
const codes = (resultSet as relationalStore.ResultSet).getBlob((resultSet as relationalStore.ResultSet).getColumnIndex("CODES"));
}

getValue20+

getValue(columnIndex: number): ValueType

获取当前行中指定列的值,如果值类型是ValueType中指定的任意类型,返回指定类型的值,否则返回14800000。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
columnIndex number 指定的列索引,从0开始。

返回值:

类型 说明
ValueType 表示允许的数据字段类型。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800012 ResultSet is empty or pointer index is out of bounds.
14800013 Resultset is empty or column index is out of bounds.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800022 SQLite: Callback routine requested an abort.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800030 SQLite: Unable to open the database file.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800032 SQLite: Abort due to constraint violation.
14800033 SQLite: Data type mismatch.
14800034 SQLite: Library used incorrectly.

示例:

if (resultSet != undefined) {
  const codes = (resultSet as relationalStore.ResultSet).getValue((resultSet as relationalStore.ResultSet).getColumnIndex("BIGINT_COLUMN"));
}

getString

getString(columnIndex: number): string

以字符串形式获取当前行中指定列的值。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
columnIndex number 指定的列索引,从0开始。

返回值:

类型 说明
string 以字符串形式返回指定列的值。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800013 The column value is null or the column type is incompatible.

示例:

if(resultSet != undefined) {
const name = (resultSet as relationalStore.ResultSet).getString((resultSet as relationalStore.ResultSet).getColumnIndex("NAME"));
}

getLong

getLong(columnIndex: number): number

以Long形式获取当前行中指定列的值。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
columnIndex number 指定的列索引,从0开始。

返回值:

类型 说明
number 以Long形式返回指定列的值。
该接口支持的数据范围是:Number.MIN_SAFE_INTEGER ~ Number.MAX_SAFE_INTEGER,若超出该范围,建议使用getDouble

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800013 The column value is null or the column type is incompatible.

示例:

if(resultSet != undefined) {
const age = (resultSet as relationalStore.ResultSet).getLong((resultSet as relationalStore.ResultSet).getColumnIndex("AGE"));
}

getDouble

getDouble(columnIndex: number): number

以double形式获取当前行中指定列的值。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
columnIndex number 指定的列索引,从0开始。

返回值:

类型 说明
number 以double形式返回指定列的值。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800013 The column value is null or the column type is incompatible.

示例:

if(resultSet != undefined) {
const salary = (resultSet as relationalStore.ResultSet).getDouble((resultSet as relationalStore.ResultSet).getColumnIndex("SALARY"));
}

getAsset10+

getAsset(columnIndex: number): Asset

Asset形式获取当前行中指定列的值。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
columnIndex number 指定的列索引,从0开始。

返回值:

类型 说明
Asset 以Asset形式返回指定列的值。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800013 The column value is null or the column type is incompatible.

示例:

if(resultSet != undefined) {
const doc = (resultSet as relationalStore.ResultSet).getAsset((resultSet as relationalStore.ResultSet).getColumnIndex("DOC"));
}

getAssets10+

getAssets(columnIndex: number): Assets

Assets形式获取当前行中指定列的值。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
columnIndex number 指定的列索引,从0开始。

返回值:

类型 说明
Assets 以Assets形式返回指定列的值。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800013 The column value is null or the column type is incompatible.

示例:

if(resultSet != undefined) {
const docs = (resultSet as relationalStore.ResultSet).getAssets((resultSet as relationalStore.ResultSet).getColumnIndex("DOCS"));
}

getRow20+

getRow(): ValuesBucket

获取当前行。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值:

类型 说明
ValuesBucket 返回指定行的值。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800012 ResultSet is empty or pointer index is out of bounds.
14800013 Resultset is empty or column index is out of bounds.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800022 SQLite: Callback routine requested an abort.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800030 SQLite: Unable to open the database file.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800032 SQLite: Abort due to constraint violation.
14800033 SQLite: Data type mismatch.
14800034 SQLite: Library used incorrectly.

示例:

if (resultSet != undefined) {
  const row = (resultSet as relationalStore.ResultSet).getRow();
}

isColumnNull

isColumnNull(columnIndex: number): boolean

检查当前行中指定列的值是否为null。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
columnIndex number 指定的列索引,从0开始。

返回值:

类型 说明
boolean 如果当前行中指定列的值为null,则返回true,否则返回false。

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800013 The column value is null or the column type is incompatible.

示例:

if(resultSet != undefined) {
const isColumnNull = (resultSet as relationalStore.ResultSet).isColumnNull((resultSet as relationalStore.ResultSet).getColumnIndex("CODES"));
}

close

close(): void

关闭结果集。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

示例:

if(resultSet != undefined) {
(resultSet as relationalStore.ResultSet).close();
}

错误码:

以下错误码的详细介绍请参见关系型数据库错误码

错误码ID 错误信息
14800012 The result set is empty or the specified location is invalid.

Transaction20+

提供以事务方式管理数据库的方法。事务对象是通过createTransaction接口创建的,不同事务对象之间的操作是隔离的,不同类型事务的区别见TransactionType

当前关系型数据库同一时刻仅支持一个写事务,所以如果当前RdbStore存在写事务未释放,创建IMMEDIATE或EXCLUSIVE事务会返回14800024错误码。如果是创建的DEFERRED事务,则可能在首次使用DEFERRED事务调用写操作时返回14800024错误码。通过IMMEDIATE或EXCLUSIVE创建写事务或者DEFERRED事务升级到写事务之后,RdbStore的写操作也会返回14800024错误码。

当事务并发量较高且写事务持续时间较长时,返回14800024错误码的次数可能会变多,开发者可以通过减少事务占用时长减少14800024出现的次数,也可以通过重试的方式处理14800024错误码。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

示例:

import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
import { window } from '@kit.ArkUI';

let store: relationalStore.RdbStore | undefined = undefined;

class EntryAbility extends UIAbility {
  async onWindowStageCreate(windowStage: window.WindowStage) {
    const STORE_CONFIG: relationalStore.StoreConfig = {
      name: "RdbTest.db",
      securityLevel: relationalStore.SecurityLevel.S3
    };

    await relationalStore.getRdbStore(this.context, STORE_CONFIG).then(async (rdbStore: relationalStore.RdbStore) => {
      store = rdbStore;
      console.info('Get RdbStore successfully.');
    }).catch((err: BusinessError) => {
      console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`);
    });

    if (store != undefined) {
      (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
        console.info(`createTransaction success`);
        // 成功获取到事务对象后执行后续操作
      }).catch((err: BusinessError) => {
        console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
      });
    }
  }
}

commit20+

commit(): Promise<void>

提交已执行的SQL语句。如果是使用异步接口执行sql语句,请确保异步接口执行完成之后再调用commit接口,否则可能会丢失SQL操作。调用commit接口之后,该Transaction对象及创建的ResultSet对象都将被关闭。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值

类型 说明
Promise<void> 无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.

示例:

let value1 = "Lisa";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3]);

if (store != undefined) {
  const valueBucket: relationalStore.ValuesBucket = {
    'NAME': value1,
    'AGE': value2,
    'SALARY': value3,
    'CODES': value4
  };
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    transaction.execute("DELETE FROM TEST WHERE age = ? OR age = ?", ["18", "20"]).then(() => {
      transaction.commit();
    }).catch((e: BusinessError) => {
      transaction.rollback();
      console.error(`execute sql failed, code is ${e.code},message is ${e.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

rollback20+

rollback(): Promise<void>

回滚已经执行的SQL语句。调用rollback接口之后,该Transaction对象及创建的ResultSet对象都会被关闭。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

返回值

类型 说明
Promise<void> 无返回结果的Promise对象。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.

示例:

if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    transaction.execute("DELETE FROM TEST WHERE age = ? OR age = ?", ["18", "20"]).then(() => {
      transaction.commit();
    }).catch((e: BusinessError) => {
      transaction.rollback();
      console.error(`execute sql failed, code is ${e.code},message is ${e.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

insert20+

insert(table: string, values: ValuesBucket, conflict?: ConflictResolution): Promise<number>

向目标表中插入一行数据,使用Promise异步回调。由于共享内存大小限制为2Mb,因此单条数据的大小需小于2Mb,否则会查询失败。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
table string 指定的目标表名。
values ValuesBucket 表示要插入到表中的数据行。
conflict ConflictResolution 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。

返回值

类型 说明
Promise<number> Promise对象。如果操作成功,返回行ID;否则返回-1。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

示例:

let value1 = "Lisa";
let value2 = 18;
let value3 = 100.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);

// 以下三种方式可用
const valueBucket1: relationalStore.ValuesBucket = {
  'NAME': value1,
  'AGE': value2,
  'SALARY': value3,
  'CODES': value4
};
const valueBucket2: relationalStore.ValuesBucket = {
  NAME: value1,
  AGE: value2,
  SALARY: value3,
  CODES: value4
};
const valueBucket3: relationalStore.ValuesBucket = {
  "NAME": value1,
  "AGE": value2,
  "SALARY": value3,
  "CODES": value4
};

if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    transaction.insert("EMPLOYEE", valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then((rowId: number) => {
      transaction.commit();
      console.info(`Insert is successful, rowId = ${rowId}`);
    }).catch((e: BusinessError) => {
      transaction.rollback();
      console.error(`Insert is failed, code is ${e.code},message is ${e.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

batchInsert20+

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

向目标表中插入一组数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
table string 指定的目标表名。
values Array<ValuesBucket> 表示要插入到表中的一组数据。

返回值

类型 说明
Promise<number> Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

示例:

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: relationalStore.ValuesBucket = {
  'NAME': value1,
  'AGE': value2,
  'SALARY': value3,
  'CODES': value4
};
const valueBucket2: relationalStore.ValuesBucket = {
  'NAME': value5,
  'AGE': value6,
  'SALARY': value7,
  'CODES': value8
};
const valueBucket3: relationalStore.ValuesBucket = {
  'NAME': value9,
  'AGE': value10,
  'SALARY': value11,
  'CODES': value12
};

let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3);
if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    transaction.batchInsert("EMPLOYEE", valueBuckets).then((insertNum: number) => {
      transaction.commit();
      console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
    }).catch((e: BusinessError) => {
      transaction.rollback();
      console.error(`batchInsert is failed, code is ${e.code},message is ${e.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

batchInsertSync20+

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

向目标表中插入一组数据。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
table string 指定的目标表名。
values Array<ValuesBucket> 表示要插入到表中的一组数据。

返回值

类型 说明
number 如果操作成功,返回插入的数据个数,否则返回-1。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

示例:

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: relationalStore.ValuesBucket = {
  'NAME': value1,
  'AGE': value2,
  'SALARY': value3,
  'CODES': value4
};
const valueBucket2: relationalStore.ValuesBucket = {
  'NAME': value5,
  'AGE': value6,
  'SALARY': value7,
  'CODES': value8
};
const valueBucket3: relationalStore.ValuesBucket = {
  'NAME': value9,
  'AGE': value10,
  'SALARY': value11,
  'CODES': value12
};

let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3);
if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    try {
      let insertNum: number = (transaction as relationalStore.Transaction).batchInsertSync("EMPLOYEE", valueBuckets);
      transaction.commit();
      console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
    } catch (e) {
      transaction.rollback();
      console.error(`batchInsert is failed, code is ${e.code},message is ${e.message}`);
    };
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

batchInsertWithConflictResolution20+

batchInsertWithConflictResolution(table: string, values: Array<ValuesBucket>, conflict: ConflictResolution): Promise<number>

向目标表中插入一组数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
table string 指定的目标表名。
values Array<ValuesBucket> 表示要插入到表中的一组数据。
conflict ConflictResolution 指定冲突解决模式。如果是ON_CONFLICT_ROLLBACK模式,当发生冲突时会回滚整个事务。

返回值

类型 说明
Promise<number> Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800022 SQLite: Callback routine requested an abort.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800032 SQLite: Abort due to constraint violation.
14800033 SQLite: Data type mismatch.
14800034 SQLite: Library used incorrectly.
14800047 The WAL file size exceeds the default limit.

示例:

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: relationalStore.ValuesBucket = {
  'NAME': value1,
  'AGE': value2,
  'SALARY': value3,
  'CODES': value4
};
const valueBucket2: relationalStore.ValuesBucket = {
  'NAME': value5,
  'AGE': value6,
  'SALARY': value7,
  'CODES': value8
};
const valueBucket3: relationalStore.ValuesBucket = {
  'NAME': value9,
  'AGE': value10,
  'SALARY': value11,
  'CODES': value12
};

let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3);
if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    transaction.batchInsertWithConflictResolution("EMPLOYEE", valueBuckets, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then((insertNum: number) => {
      transaction.commit();
      console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
    }).catch((e: BusinessError) => {
      transaction.rollback();
      console.error(`batchInsert is failed, code is ${e.code},message is ${e.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

batchInsertWithConflictResolutionSync20+

batchInsertWithConflictResolutionSync(table: string, values: Array<ValuesBucket>, conflict: ConflictResolution): number

向目标表中插入一组数据。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
table string 指定的目标表名。
values Array<ValuesBucket> 表示要插入到表中的一组数据。
conflict ConflictResolution 指定冲突解决模式。如果是ON_CONFLICT_ROLLBACK模式,当发生冲突时会回滚整个事务。

返回值

类型 说明
number 如果操作成功,返回插入的数据个数,否则返回-1。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800022 SQLite: Callback routine requested an abort.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800032 SQLite: Abort due to constraint violation.
14800033 SQLite: Data type mismatch.
14800034 SQLite: Library used incorrectly.
14800047 The WAL file size exceeds the default limit.

示例:

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: relationalStore.ValuesBucket = {
  'NAME': value1,
  'AGE': value2,
  'SALARY': value3,
  'CODES': value4
};
const valueBucket2: relationalStore.ValuesBucket = {
  'NAME': value5,
  'AGE': value6,
  'SALARY': value7,
  'CODES': value8
};
const valueBucket3: relationalStore.ValuesBucket = {
  'NAME': value9,
  'AGE': value10,
  'SALARY': value11,
  'CODES': value12
};

let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3);
if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    try {
      let insertNum: number = (transaction as relationalStore.Transaction).batchInsertWithConflictResolutionSync("EMPLOYEE", valueBuckets, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE);
      transaction.commit();
      console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
    } catch (e) {
      transaction.rollback();
      console.error(`batchInsert is failed, code is ${e.code},message is ${e.message}`);
    };
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

update20+

update(values: ValuesBucket, predicates: RdbPredicates, conflict?: ConflictResolution): Promise<number>

根据RdbPredicates的指定实例对象更新数据库中的数据,使用Promise异步回调。由于共享内存大小限制为2Mb,因此单条数据的大小需小于2Mb,否则会查询失败。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
values ValuesBucket values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。
predicates RdbPredicates RdbPredicates的实例对象指定的更新条件。
conflict ConflictResolution 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。

返回值

类型 说明
Promise<number> 指定的Promise回调方法。返回受影响的行数。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

示例:

let value1 = "Rose";
let value2 = 22;
let value3 = 200.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);

// 以下三种方式可用
const valueBucket1: relationalStore.ValuesBucket = {
  'NAME': value1,
  'AGE': value2,
  'SALARY': value3,
  'CODES': value4
};
const valueBucket2: relationalStore.ValuesBucket = {
  NAME: value1,
  AGE: value2,
  SALARY: value3,
  CODES: value4
};
const valueBucket3: relationalStore.ValuesBucket = {
  "NAME": value1,
  "AGE": value2,
  "SALARY": value3,
  "CODES": value4
};

let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.equalTo("NAME", "Lisa");

if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    transaction.update(valueBucket1, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE).then(async (rows: Number) => {
      transaction.commit();
      console.info(`Updated row count: ${rows}`);
    }).catch((e: BusinessError) => {
      transaction.rollback();
      console.error(`Updated failed, code is ${e.code},message is ${e.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

updateSync20+

updateSync(values: ValuesBucket, predicates: RdbPredicates, conflict?: ConflictResolution): number

根据RdbPredicates的指定实例对象更新数据库中的数据。由于共享内存大小限制为2Mb,因此单条数据的大小需小于2Mb,否则会查询失败。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
values ValuesBucket values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。
predicates RdbPredicates RdbPredicates的实例对象指定的更新条件。
conflict ConflictResolution 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。

返回值

类型 说明
number 返回受影响的行数。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

示例:

let value1 = "Rose";
let value2 = 22;
let value3 = 200.5;
let value4 = new Uint8Array([1, 2, 3, 4, 5]);

// 以下三种方式可用
const valueBucket1: relationalStore.ValuesBucket = {
  'NAME': value1,
  'AGE': value2,
  'SALARY': value3,
  'CODES': value4
};
const valueBucket2: relationalStore.ValuesBucket = {
  NAME: value1,
  AGE: value2,
  SALARY: value3,
  CODES: value4
};
const valueBucket3: relationalStore.ValuesBucket = {
  "NAME": value1,
  "AGE": value2,
  "SALARY": value3,
  "CODES": value4
};

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");

if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    try {
      let rows: Number = (transaction as relationalStore.Transaction).updateSync(valueBucket1, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE);
      transaction.commit();
      console.info(`Updated row count: ${rows}`);
    } catch (e) {
      transaction.rollback();
      console.error(`Updated failed, code is ${e.code},message is ${e.message}`);
    };
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

delete20+

delete(predicates: RdbPredicates):Promise<number>

根据RdbPredicates的指定实例对象从数据库中删除数据,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
predicates RdbPredicates RdbPredicates的实例对象指定的删除条件。

返回值

类型 说明
Promise<number> Promise对象。返回受影响的行数。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

示例:

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");

if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    transaction.delete(predicates).then((rows: Number) => {
      transaction.commit();
      console.info(`Delete rows: ${rows}`);
    }).catch((e: BusinessError) => {
      transaction.rollback();
      console.error(`Delete failed, code is ${e.code},message is ${e.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

deleteSync20+

deleteSync(predicates: RdbPredicates): number

根据RdbPredicates的指定实例对象从数据库中删除数据。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
predicates RdbPredicates RdbPredicates的实例对象指定的删除条件。

返回值

类型 说明
number 返回受影响的行数。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

示例:

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Lisa");

if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    try {
      let rows: Number = (transaction as relationalStore.Transaction).deleteSync(predicates);
      transaction.commit();
      console.info(`Delete rows: ${rows}`);
    } catch (e) {
      transaction.rollback();
      console.error(`Delete failed, code is ${e.code},message is ${e.message}`);
    };
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

query20+

query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet>

根据指定条件查询数据库中的数据,使用Promise异步回调。由于共享内存大小限制为2Mb,因此单条数据的大小需小于2Mb,否则会查询失败。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
predicates RdbPredicates RdbPredicates的实例对象指定的查询条件。
columns Array<string> 表示要查询的列。如果值为空,则查询应用于所有列。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800026 SQLite: The database is out of memory.
14800028 SQLite: Some kind of disk I/O error occurred.
14800047 The WAL file size exceeds the default limit.

返回值

类型 说明
Promise<ResultSet> Promise对象。如果操作成功,则返回ResultSet对象。

示例:

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose");

if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    transaction.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then(async (resultSet: relationalStore.ResultSet) => {
      console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
      // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
      while (resultSet.goToNextRow()) {
        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"));
        console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
      }
      // 释放数据集的内存,若不释放可能会引起fd泄露与内存泄露
      resultSet.close();
      transaction.commit();
    }).catch((e: BusinessError) => {
      transaction.rollback();
      console.error(`Query failed, code is ${e.code},message is ${e.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

querySync20+

querySync(predicates: RdbPredicates, columns?: Array<string>): ResultSet

根据指定条件查询数据库中的数据。对query同步接口获得的resultSet进行操作时,若逻辑复杂且循环次数过多,可能造成freeze问题,建议将此步骤放到taskpool线程中执行。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
predicates RdbPredicates RdbPredicates的实例对象指定的查询条件。
columns Array<string> 表示要查询的列。如果值为空,则查询应用于所有列。默认值为空。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800028 SQLite: Some kind of disk I/O error occurred.
14800047 The WAL file size exceeds the default limit.

返回值

类型 说明
ResultSet 如果操作成功,则返回ResultSet对象。

示例:

let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
predicates.equalTo("NAME", "Rose");

if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then(async (transaction: relationalStore.Transaction) => {
    try {
      let resultSet: relationalStore.ResultSet = (transaction as relationalStore.Transaction).querySync(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
      console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
      // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
      while (resultSet.goToNextRow()) {
        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"));
        console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
      }
      // 释放数据集的内存,若不释放可能会引起fd泄露与内存泄露
      resultSet.close();
      transaction.commit();
    } catch (e) {
      transaction.rollback();
      console.error(`Query failed, code is ${e.code},message is ${e.message}`);
    };
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

querySql20+

querySql(sql: string, args?: Array<ValueType>): Promise<ResultSet>

根据指定SQL语句查询数据库中的数据,SQL语句中的各种表达式和操作符之间的关系操作符号不超过1000个,使用Promise异步回调。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
sql string 指定要执行的SQL语句。
args Array<ValueType> SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。

返回值

类型 说明
Promise<ResultSet> Promise对象。如果操作成功,则返回ResultSet对象。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800028 SQLite: Some kind of disk I/O error occurred.
14800047 The WAL file size exceeds the default limit.

示例:

if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    transaction.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'").then(async (resultSet: relationalStore.ResultSet) => {
      console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
      // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
      while (resultSet.goToNextRow()) {
        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"));
        console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
      }
      // 释放数据集的内存,若不释放可能会引起fd泄露与内存泄露
      resultSet.close();
      transaction.commit();
    }).catch((e: BusinessError) => {
      transaction.rollback();
      console.error(`Query failed, code is ${e.code},message is ${e.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

querySqlSync20+

querySqlSync(sql: string, args?: Array<ValueType>): ResultSet

根据指定SQL语句查询数据库中的数据,SQL语句中的各种表达式和操作符之间的关系操作符号不超过1000个。对query同步接口获得的resultSet进行操作时,若逻辑复杂且循环次数过多,可能造成freeze问题,建议将此步骤放到taskpool线程中执行。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
sql string 指定要执行的SQL语句。
args Array<ValueType> SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。默认值为空。

返回值

类型 说明
ResultSet 如果操作成功,则返回ResultSet对象。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800028 SQLite: Some kind of disk I/O error occurred.
14800047 The WAL file size exceeds the default limit.

示例:

if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then(async (transaction: relationalStore.Transaction) => {
    try {
      let resultSet: relationalStore.ResultSet = (transaction as relationalStore.Transaction).querySqlSync("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'");
      console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
      // resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
      while (resultSet.goToNextRow()) {
        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"));
        console.info(`id=${id}, name=${name}, age=${age}, salary=${salary}`);
      }
      // 释放数据集的内存,若不释放可能会引起fd泄露与内存泄露
      resultSet.close();
      transaction.commit();
    } catch (e) {
      transaction.rollback();
      console.error(`Query failed, code is ${e.code},message is ${e.message}`);
    };
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

execute20+

execute(sql: string, args?: Array<ValueType>): Promise<ValueType>

执行包含指定参数的SQL语句,语句中的各种表达式和操作符之间的关系操作符号不超过1000个,返回值类型为ValueType,使用Promise异步回调。

该接口支持执行增删改操作,支持执行PRAGMA语法的sql,支持对表的操作(建表、删表、修改表),返回结果类型由执行具体sql的结果决定。

此接口不支持执行查询、附加数据库和事务操作,查询可以使用querySqlquery接口代替、附加数据库可以使用attach接口代替。

不支持分号分隔的多条语句。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
sql string 指定要执行的SQL语句。
args Array<ValueType> SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。

返回值

类型 说明
Promise<ValueType> Promise对象,返回sql执行后的结果。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported the sql(attach,begin,commit,rollback etc.).
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

示例:

// 删除表中所有数据
if (store != undefined) {
  const SQL_DELETE_TABLE = 'DELETE FROM test';
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    transaction.execute(SQL_DELETE_TABLE).then((data) => {
      transaction.commit();
      console.info(`delete result: ${data}`);
    }).catch((e: BusinessError) => {
      transaction.rollback();
      console.error(`delete failed, code is ${e.code}, message is ${e.message}`);
    });
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}

executeSync20+

executeSync(sql: string, args?: Array<ValueType>): ValueType

执行包含指定参数的SQL语句,语句中的各种表达式和操作符之间的关系操作符号不超过1000个,返回值类型为ValueType。

该接口支持执行增删改操作,支持执行PRAGMA语法的sql,支持对表的操作(建表、删表、修改表),返回结果类型由执行具体sql的结果决定。

此接口不支持执行查询、附加数据库和事务操作,查询可以使用querySqlquery接口代替、附加数据库可以使用attach接口代替。

不支持分号分隔的多条语句。

系统能力: SystemCapability.DistributedDataManager.RelationalStore.Core

参数:

参数名 类型 必填 说明
sql string 指定要执行的SQL语句。
args Array<ValueType> SQL语句中参数的值。该值与sql参数语句中的占位符相对应。该参数不填,或者填null或undefined,都认为是sql参数语句完整。默认值为空。

返回值

类型 说明
ValueType 返回sql执行后的结果。

错误码:

以下错误码的详细介绍请参见通用错误码关系型数据库错误码。其中,14800011错误码处理可参考数据库备份与恢复

错误码ID 错误信息
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types.
801 Capability not supported the sql(attach,begin,commit,rollback etc.).
14800000 Inner error.
14800011 Failed to open the database because it is corrupted.
14800014 The RdbStore or ResultSet is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800023 SQLite: Access permission denied.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800026 SQLite: The database is out of memory.
14800027 SQLite: Attempt to write a readonly database.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800031 SQLite: TEXT or BLOB exceeds size limit.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

示例:

// 删除表中所有数据
if (store != undefined) {
  (store as relationalStore.RdbStore).createTransaction().then((transaction: relationalStore.Transaction) => {
    const SQL_DELETE_TABLE = 'DELETE FROM test';
    try {
      let data = (transaction as relationalStore.Transaction).executeSync(SQL_DELETE_TABLE);
      transaction.commit();
      console.info(`delete result: ${data}`);
    } catch (e) {
      transaction.rollback();
      console.error(`delete failed, code is ${e.code}, message is ${e.message}`);
    };
  }).catch((err: BusinessError) => {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  });
}