Interface (Transaction)

Provides APIs for managing databases in transaction mode. A transaction object is created by using createTransaction. Operations on different transaction objects are isolated. For details about the transaction types, see TransactionType.

Currently, an RDB store supports only one write transaction at a time. If the current RdbStore has a write transaction that is not released, creating an IMMEDIATE or EXCLUSIVE transaction object will return error 14800024. If a DEFERRED transaction object is created, error 14800024 may be returned when it is used to invoke a write operation for the first time. After a write transaction is created using IMMEDIATE or EXCLUSIVE, or a DEFERRED transaction is upgraded to a write transaction, write operations in the RdbStore will also return error 14800024.

When the number of concurrent transactions is large and the write transaction duration is long, the frequency of returning error 14800024 may increase. You can reduce the occurrence of error 14800024 by shortening the transaction duration or by handling the error 14800024 through retries.

Before using the following APIs, you should obtain a Transaction instance by calling the createTransaction method and then call the corresponding method through the instance.

NOTE

  • The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.

  • The initial APIs of this module are supported since API version 14.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Example:

For details about the definition of this.context in the sample code, see the application context of the stage model.

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

let store: relationalStore.RdbStore | undefined = undefined;

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

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

    if (store != undefined) {
      await store.executeSql('CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB, IDENTITY UNLIMITED INT, ASSETDATA ASSET, ASSETSDATA ASSETS, FLOATARRAY floatvector(128))');
      store.createTransaction().then(async (transaction: relationalStore.Transaction) => {
        console.info(`createTransaction success`);
        // Perform subsequent operations after the transaction instance is successfully obtained.
      }).catch((err: BusinessError) => {
        console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
      });
    }
  }
}

Module to Import

import { relationalStore } from '@kit.ArkData';

commit14+

commit(): Promise<void>

Commits this executed SQL statement. This API uses a promise to return the result. When using asynchronous APIs to execute SQL statements, ensure that commit() is called after the asynchronous API execution is completed. Otherwise, the SQL operations may be lost. After commit() is called, the transaction object and the created ResultSet object will be closed.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Return value

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

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      await transaction.execute('CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER, salary REAL)');
      await transaction.commit();
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`execute sql failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

rollback14+

rollback(): Promise<void>

Rolls back this executed SQL statement. This API uses a promise to return the result. After rollback() is called, the transaction object and the created ResultSet object will be closed.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Return value

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

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      await transaction.execute('DELETE FROM TEST WHERE age = ? OR age = ?', ['18', '20']);
      await transaction.commit();
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`execute sql failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

insert14+

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

Inserts a row of data into a table. This API uses a promise to return the result. Due to the limit of the shared memory, the size of a single data record cannot exceed 2 MB. Otherwise, data cannot be obtained using the get methods such as getValue and getString after ResultSet is obtained through the query or querySql API of RdbStore. As a result, the operation may fail or an exception may be thrown.

A single string field supports a maximum of 8 MB data. If the data exceeds 8 MB, only the first 8 MB data is retained. For data storage requirements exceeding 8 MB, the Blob type is recommended.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
table string Yes Name of the target table.
values ValuesBucket Yes Row of data to insert.
conflict ConflictResolution No Resolution used to resolve the conflict.
Default value: relationalStore.ConflictResolution.ON_CONFLICT_NONE.

Return value

Type Description
Promise<number> Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, -1 will be returned.

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

const valueBucket1: relationalStore.ValuesBucket = {
  NAME: 'Lisa',
  AGE: 18,
  SALARY: 100.5,
  CODES: new Uint8Array([1, 2, 3, 4, 5])
};

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      const rowId = await transaction.insert('EMPLOYEE', valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE);
      await transaction.commit();
      console.info(`Insert is successful, rowId = ${rowId}`);
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`Insert is failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

insertSync14+

insertSync(table: string, values: ValuesBucket | sendableRelationalStore.ValuesBucket, conflict?: ConflictResolution): number

Inserts a row of data into a table. This API returns the result synchronously. Due to the limit of the shared memory, the size of a single data record cannot exceed 2 MB. Otherwise, data cannot be obtained using the get methods such as getValue and getString after ResultSet is obtained through the query or querySql API of RdbStore. As a result, the operation may fail or an exception may be thrown.

A single string field supports a maximum of 8 MB data. If the data exceeds 8 MB, only the first 8 MB data is retained. For data storage requirements exceeding 8 MB, the Blob type is recommended.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
table string Yes Name of the target table.
values ValuesBucket | sendableRelationalStore.ValuesBucket Yes Row of data to insert.
conflict ConflictResolution No Resolution used to resolve the conflict.
Default value: relationalStore.ConflictResolution.ON_CONFLICT_NONE.

Return value

Type Description
number If the operation is successful, the row ID will be returned. Otherwise, -1 will be returned.

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

let value5 = 'Lisa';
let value6 = 18;
let value7 = 100.5;
let value8 = new Uint8Array([1, 2, 3, 4, 5]);

const valueBucket2: relationalStore.ValuesBucket = {
  NAME: value5,
  AGE: value6,
  SALARY: value7,
  CODES: value8
};
if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      let rowId: number = transaction.insertSync(
        'EMPLOYEE',
        valueBucket2,
        relationalStore.ConflictResolution.ON_CONFLICT_REPLACE
      );
      await transaction.commit();
      console.info(`Insert is successful, rowId = ${rowId}`);
    } catch (e) {
      await transaction.rollback();
      console.error(`Insert is failed, code is ${e.code},message is ${e.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

batchInsert14+

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

Inserts data into a table in batches. This API uses a promise to return the result.

Data is written in batches of up to 32,766 parameters each with the ConflictResolution.ON_CONFLICT_REPLACE policy. The total number of parameters is calculated as the number of inserted data records multiplied by the size of the union set of all fields in the inserted data. If the operation fails, an error is returned.

A single string field supports a maximum of 8 MB data. If the data exceeds 8 MB, only the first 8 MB data is retained. For data storage requirements exceeding 8 MB, the Blob type is recommended.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
table string Yes Name of the target table.
values Array<ValuesBucket> Yes An array of data to insert.

Return value

Type Description
Promise<number> Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, -1 is returned.

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

const valueBucket3: relationalStore.ValuesBucket = {
  NAME: 'Lisa',
  AGE: 18,
  SALARY: 100.5,
  CODES: new Uint8Array([1, 2, 3, 4, 5])
};
const valueBucket4: relationalStore.ValuesBucket = {
  NAME: 'Jack',
  AGE: 19,
  SALARY: 101.5,
  CODES: new Uint8Array([6, 7, 8, 9, 10])
};
const valueBucket5: relationalStore.ValuesBucket = {
  NAME: 'Tom',
  AGE: 20,
  SALARY: 102.5,
  CODES: new Uint8Array([11, 12, 13, 14, 15])
};

let valueBuckets = new Array(valueBucket3, valueBucket4, valueBucket5);
if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      const insertNum = await transaction.batchInsert('EMPLOYEE', valueBuckets);
      await transaction.commit();
      console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

batchInsertSync14+

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

Inserts data into a table in batches. This API returns the result synchronously.

Data is written in batches of up to 32,766 parameters each with the ConflictResolution.ON_CONFLICT_REPLACE policy. The total number of parameters is calculated as the number of inserted data records multiplied by the size of the union set of all fields in the inserted data. If the operation fails, an error is returned.

A single string field supports a maximum of 8 MB data. If the data exceeds 8 MB, only the first 8 MB data is retained. For data storage requirements exceeding 8 MB, the Blob type is recommended.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
table string Yes Name of the target table.
values Array<ValuesBucket> Yes An array of data to insert.

Return value

Type Description
number If the operation is successful, the number of inserted data records is returned. Otherwise, -1 is returned.

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

const valueBucket6: relationalStore.ValuesBucket = {
  NAME: 'Lisa',
  AGE: 18,
  SALARY: 100.5,
  CODES: new Uint8Array([1, 2, 3, 4, 5])
};
const valueBucket7: relationalStore.ValuesBucket = {
  NAME: 'Jack',
  AGE: 19,
  SALARY: 101.5,
  CODES: new Uint8Array([6, 7, 8, 9, 10])
};
const valueBucket8: relationalStore.ValuesBucket = {
  NAME: 'Tom',
  AGE: 20,
  SALARY: 102.5,
  CODES: new Uint8Array([11, 12, 13, 14, 15])
};

let valueBuckets2 = new Array(valueBucket6, valueBucket7, valueBucket8);
if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      let insertNum: number = (transaction as relationalStore.Transaction).batchInsertSync('EMPLOYEE', valueBuckets2);
      await transaction.commit();
      console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

batchInsertWithConflictResolution18+

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

Inserts data into a table with conflict resolutions in batches. You can use the conflict parameter to specify ConflictResolution. This API uses a promise to return the result.

A maximum of 32,766 parameters can be inserted at a time. If the number of parameters exceeds this limit, the error code 14800000 is returned. The number of inserted data records multiplied by the size of the union across all fields in the inserted data equals the number of parameters.

For example, if the size of the union set is 10, a maximum of 3,276 data records can be inserted (3276 × 10 = 32760).

Ensure that your application complies with this constraint when calling this API to avoid errors caused by excessive parameters.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
table string Yes Name of the target table.
values Array<ValuesBucket> Yes An array of data to insert.
conflict ConflictResolution Yes Resolution used to resolve the conflict. If ON_CONFLICT_ROLLBACK is used, the transaction will be rolled back when a conflict occurs.

Return value

Type Description
Promise<number> Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, -1 is returned.

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

const valueBucket9: relationalStore.ValuesBucket = {
  NAME: 'Lisa',
  AGE: 18,
  SALARY: 100.5,
  CODES: new Uint8Array([1, 2, 3, 4, 5])
};
const valueBucketA: relationalStore.ValuesBucket = {
  NAME: 'Jack',
  AGE: 19,
  SALARY: 101.5,
  CODES: new Uint8Array([6, 7, 8, 9, 10])
};
const valueBucketB: relationalStore.ValuesBucket = {
  NAME: 'Tom',
  AGE: 20,
  SALARY: 102.5,
  CODES: new Uint8Array([11, 12, 13, 14, 15])
};

let valueBuckets3 = new Array(valueBucket9, valueBucketA, valueBucketB);

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      const insertNum = await transaction.batchInsertWithConflictResolution(
        'EMPLOYEE',
        valueBuckets3,
        relationalStore.ConflictResolution.ON_CONFLICT_REPLACE
      );
      await transaction.commit();
      console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

batchInsertWithConflictResolutionSync18+

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

Inserts data into a table with conflict resolutions in batches. You can use the conflict parameter to specify ConflictResolution.

A maximum of 32,766 parameters can be inserted at a time. If the number of parameters exceeds this limit, the error code 14800000 is returned. The number of inserted data records multiplied by the size of the union across all fields in the inserted data equals the number of parameters.

For example, if the size of the union set is 10, a maximum of 3,276 data records can be inserted (3276 × 10 = 32760).

Ensure that your application complies with this constraint when calling this API to avoid errors caused by excessive parameters.

A single string field supports a maximum of 8 MB data. If the data exceeds 8 MB, only the first 8 MB data is retained. For data storage requirements exceeding 8 MB, the Blob type is recommended.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
table string Yes Name of the target table.
values Array<ValuesBucket> Yes An array of data to insert.
conflict ConflictResolution Yes Resolution used to resolve the conflict. If ON_CONFLICT_ROLLBACK is used, the transaction will be rolled back when a conflict occurs.

Return value

Type Description
number If the operation is successful, the number of inserted data records is returned. Otherwise, -1 is returned.

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

const valueBucketC: relationalStore.ValuesBucket = {
  NAME: 'Lisa',
  AGE: 18,
  SALARY: 100.5,
  CODES: new Uint8Array([1, 2, 3, 4, 5])
};
const valueBucketD: relationalStore.ValuesBucket = {
  NAME: 'Jack',
  AGE: 19,
  SALARY: 101.5,
  CODES: new Uint8Array([6, 7, 8, 9, 10])
};
const valueBucketE: relationalStore.ValuesBucket = {
  NAME: 'Tom',
  AGE: 20,
  SALARY: 102.5,
  CODES: new Uint8Array([11, 12, 13, 14, 15])
};

let valueBuckets4 = new Array(valueBucketC, valueBucketD, valueBucketE);
if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      const insertNum = transaction.batchInsertWithConflictResolutionSync(
        'EMPLOYEE',
        valueBuckets4,
        relationalStore.ConflictResolution.ON_CONFLICT_REPLACE
      );
      await transaction.commit();
      console.info(`batchInsert is successful, the number of values that were inserted = ${insertNum}`);
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`batchInsert is failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

batchInsertWithReturning23+

batchInsertWithReturning(table: string, values: Array<ValuesBucket>, config: ReturningConfig, conflict?: ConflictResolution): Promise<Result>

Inserts data into a table in batches. You can use the conflict parameter to specify ConflictResolution, and Result is returned. This API uses a promise to return the result.

A maximum of 32,766 parameters can be inserted at a time. If the number of parameters exceeds this limit, the error code 14800001 is returned. The number of inserted data records multiplied by the size of the union across all fields in the inserted data equals the number of parameters.

For example, if the size of the union set is 10, a maximum of 3,276 data records can be inserted (3276 × 10 = 32760).

Ensure that your application complies with this constraint when calling this API to avoid errors caused by excessive parameters.

It is not recommended to use the ON_CONFLICT_FAIL policy for the conflict parameter, as this may prevent the return of correct results.

A single string field supports a maximum of 8 MB data. If the data exceeds 8 MB, only the first 8 MB data is retained. For data storage requirements exceeding 8 MB, the Blob type is recommended.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Model restriction: This API can be used only in the stage model.

Parameters

Name Type Mandatory Description
table string Yes Name of the target table for data insertion. Note: A valid table name must not contain spaces ( ), commas (,), or asterisks (*), and must not start or end with a dot (.). Otherwise, a parameter error will be thrown.
values Array<ValuesBucket> Yes An array of data to insert. Note: An empty array or data containing duplicate asset records will trigger a parameter error.
config ReturningConfig Yes Configuration information of the return value.
conflict ConflictResolution No Resolution used to resolve the conflict. Default value: ON_CONFLICT_NONE.

Return value

Type Description
Promise<Result> Promise used to return the result. If the operation is successful, the affected dataset is returned.

Error codes

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

ID Error Message
14800001 Invalid arguments. Possible causes: 1. Parameter is out of valid range.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800032 SQLite: Abort due to constraint violation.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

Example:

async function transBatchInsertWithReturningExample(trans: relationalStore.Transaction)
{
  const valueBucket1: relationalStore.ValuesBucket = { 'NAME': 'zhangsan', 'AGE': 18 };
  const valueBucket2: relationalStore.ValuesBucket = { 'NAME': 'lisi', 'AGE': 20 };
  const config: relationalStore.ReturningConfig = { columns: ['NAME', 'AGE'] };
  const valueBuckets = new Array(valueBucket1, valueBucket2);
  try {
    let results = await trans.batchInsertWithReturning("EMPLOYEE", valueBuckets, config);
    console.info(`transBatchInsertWithReturningExample is successful, changed is ${results.changed}`);
    while(results.resultSet.goToNextRow()) {
      const row = results.resultSet.getRow();
      console.info(`transBatchInsertWithReturningExample, name is ${row['NAME']}, age is ${row['AGE']}`);
    }
  } catch (e) {
    console.error(`transBatchInsertWithReturningExample failed. code is ${e.code}, message is ${e.message}`);
  }
}

batchInsertWithReturningSync23+

batchInsertWithReturningSync(table: string, values: Array<ValuesBucket>, config: ReturningConfig, conflict?: ConflictResolution): Result

Inserts data into a table in batches. You can use the conflict parameter to specify ConflictResolution, and Result is returned.

A maximum of 32,766 parameters can be inserted at a time. If the number of parameters exceeds this limit, the error code 14800001 is returned. The number of inserted data records multiplied by the size of the union across all fields in the inserted data equals the number of parameters.

For example, if the size of the union set is 10, a maximum of 3,276 data records can be inserted (3276 × 10 = 32760).

Ensure that your application complies with this constraint when calling this API to avoid errors caused by excessive parameters.

It is not recommended to use the ON_CONFLICT_FAIL policy for the conflict parameter, as this may prevent the return of correct results.

A single string field supports a maximum of 8 MB data. If the data exceeds 8 MB, only the first 8 MB data is retained. For data storage requirements exceeding 8 MB, the Blob type is recommended.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Model restriction: This API can be used only in the stage model.

Parameters

Name Type Mandatory Description
table string Yes Name of the target table for data insertion. Note: A valid table name must not contain spaces ( ), commas (,), or asterisks (*), and must not start or end with a dot (.). Otherwise, a parameter error will be thrown.
values Array<ValuesBucket> Yes An array of data to insert. Note: An empty array or data containing duplicate asset records will trigger a parameter error.
config ReturningConfig Yes Configuration information of the return value.
conflict ConflictResolution No Resolution used to resolve the conflict. Default value: ON_CONFLICT_NONE.

Return value

Type Description
Result If the operation is successful, the affected dataset is returned.

Error codes

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

ID Error Message
14800001 Invalid arguments. Possible causes: 1. Parameter is out of valid range.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800032 SQLite: Abort due to constraint violation.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

Example:

function transBatchInsertWithReturningSyncExample(trans: relationalStore.Transaction)
{
  const valueBucket1: relationalStore.ValuesBucket = { 'NAME': 'zhangsan', 'AGE': 18 };
  const valueBucket2: relationalStore.ValuesBucket = { 'NAME': 'lisi', 'AGE': 20 };
  const config: relationalStore.ReturningConfig = { columns: ['NAME', 'AGE'] };
  const valueBuckets = new Array(valueBucket1, valueBucket2);
  try {
    let results = trans.batchInsertWithReturningSync("EMPLOYEE", valueBuckets, config);
    console.info(`transBatchInsertWithReturningSyncExample is successful, changed is ${results.changed}`);
    while(results.resultSet.goToNextRow()) {
      const row = results.resultSet.getRow();
      console.info(`transBatchInsertWithReturningSyncExample, name is ${row['NAME']}, age is ${row['AGE']}`);
    }
  } catch (e) {
    console.error(`transBatchInsertWithReturningSyncExample failed. code is ${e.code}, message is ${e.message}`);
  }
}

update14+

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

Updates data based on the specified RdbPredicates object. This API uses a promise to return the result. Due to the limit of the shared memory, the size of a single data record cannot exceed 2 MB. Otherwise, data cannot be obtained using the get methods such as getValue and getString after ResultSet is obtained through the query or querySql API of RdbStore. As a result, the operation may fail or an exception may be thrown.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
values ValuesBucket Yes Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.
predicates RdbPredicates Yes Update conditions specified by the RdbPredicates object.
conflict ConflictResolution No Resolution used to resolve the conflict.
Default value: relationalStore.ConflictResolution.ON_CONFLICT_NONE.

Return value

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

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

const valueBucketF: relationalStore.ValuesBucket = {
  NAME: 'Rose',
  AGE: 22,
  SALARY: 200.5,
  CODES: new Uint8Array([1, 2, 3, 4, 5])
};
let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
predicates.equalTo('NAME', 'Lisa');

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      const rows = await transaction.update(valueBucketF, predicates, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE);
      await transaction.commit();
      console.info(`Updated row count: ${rows}`);
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

updateSync14+

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

Updates data in the RDB store based on the specified RdbPredicates object. This API returns the result synchronously. Due to the limit of the shared memory, the size of a single data record cannot exceed 2 MB. Otherwise, data cannot be obtained using the get methods such as getValue and getString after ResultSet is obtained through the query or querySql API of RdbStore. As a result, the operation may fail or an exception may be thrown.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
values ValuesBucket Yes Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.
predicates RdbPredicates Yes Update conditions specified by the RdbPredicates object.
conflict ConflictResolution No Resolution used to resolve the conflict.
Default value: relationalStore.ConflictResolution.ON_CONFLICT_NONE.

Return value

Type Description
number Number of rows updated.

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

const valueBucketG: relationalStore.ValuesBucket = {
  NAME: 'Rose',
  AGE: 22,
  SALARY: 200.5,
  CODES: new Uint8Array([1, 2, 3, 4, 5])
};
let predicates1 = new relationalStore.RdbPredicates('EMPLOYEE');
predicates1.equalTo('NAME', 'Lisa');

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      let rows = transaction.updateSync(valueBucketG, predicates1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE);
      await transaction.commit();
      console.info(`Updated row count: ${rows}`);
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`Updated failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

updateWithReturning23+

updateWithReturning(values: ValuesBucket, predicates: RdbPredicates, config: ReturningConfig, conflict?: ConflictResolution): Promise<Result>

Updates data in the RDB store based on the specified RdbPredicates instance object. You can use the conflict parameter to specify ConflictResolution, and Result is returned. This API uses a promise to return the result.

It is not recommended to use the ON_CONFLICT_FAIL policy for the conflict parameter, as this may prevent the return of correct results.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Model restriction: This API can be used only in the stage model.

Parameters

Name Type Mandatory Description
values ValuesBucket Yes Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.
predicates RdbPredicates Yes Update conditions specified by the RdbPredicates object.
config ReturningConfig Yes Configuration information of the return value.
conflict ConflictResolution No Resolution used to resolve the conflict. Default value: ON_CONFLICT_NONE.

Return value

Type Description
Promise<Result> Promise used to return the result. If the operation is successful, the affected dataset is returned.

Error codes

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

ID Error Message
14800001 Invalid arguments. Possible causes: 1. Parameter is out of valid range.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800032 SQLite: Abort due to constraint violation.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

Example:

async function transUpdateWithReturningExample(trans: relationalStore.Transaction)
{
  const valueBucket1: relationalStore.ValuesBucket = { 'NAME': 'lisi', 'AGE': 21 };
  const valueBucket2: relationalStore.ValuesBucket = { 'NAME': 'lisi', 'AGE': 18 };
  let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
  predicates.equalTo('NAME', 'lisi');
  const config: relationalStore.ReturningConfig = { columns: ['NAME', 'AGE'] };
  try {
    trans.batchInsertWithReturningSync("EMPLOYEE", [valueBucket1, valueBucket2], config);
    valueBucket1['NAME'] = "zhangsan";
    valueBucket1['AGE'] = 18;
    let results = await trans.updateWithReturning(valueBucket1, predicates, config);
    console.info(`transUpdateWithReturningExample is successful, changed is ${results.changed}`);
    while(results.resultSet.goToNextRow()) {
      const row = results.resultSet.getRow();
      console.info(`transUpdateWithReturningExample, name is ${row['NAME']}, age is ${row['AGE']}`);
    }
  } catch (e) {
    console.error(`transUpdateWithReturningExample failed. code is ${e.code}, message is ${e.message}`);
  }
}

updateWithReturningSync23+

updateWithReturningSync(values: ValuesBucket, predicates: RdbPredicates, config: ReturningConfig, conflict?: ConflictResolution): Result

Updates data in the RDB store based on the specified RdbPredicates instance object. You can use the conflict parameter to specify ConflictResolution, and Result is returned.

It is not recommended to use the ON_CONFLICT_FAIL policy for the conflict parameter, as this may prevent the return of correct results.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Model restriction: This API can be used only in the stage model.

Parameters

Name Type Mandatory Description
values ValuesBucket Yes Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.
predicates RdbPredicates Yes Update conditions specified by the RdbPredicates object.
config ReturningConfig Yes Configuration information of the return value.
conflict ConflictResolution No Resolution used to resolve the conflict. Default value: ON_CONFLICT_NONE.

Return value

Type Description
Result If the operation is successful, the affected dataset is returned.

Error codes

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

ID Error Message
14800001 Invalid arguments. Possible causes: 1. Parameter is out of valid range.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800032 SQLite: Abort due to constraint violation.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

Example:

function transUpdateWithReturningSyncExample(trans: relationalStore.Transaction)
{
  const valueBucket1: relationalStore.ValuesBucket = { 'NAME': 'lisi', 'AGE': 21 };
  const valueBucket2: relationalStore.ValuesBucket = { 'NAME': 'lisi', 'AGE': 18 };
  let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
  predicates.equalTo('NAME', 'lisi');
  const config: relationalStore.ReturningConfig = { columns: ['NAME', 'AGE'] };
  try {
    trans.batchInsertWithReturningSync("EMPLOYEE", [valueBucket1, valueBucket2], config);
    valueBucket1['NAME'] = "zhangsan";
    valueBucket1['AGE'] = 18;
    let results = trans.updateWithReturningSync(valueBucket1, predicates, config);
    console.info(`transUpdateWithReturningSyncExample is successful, changed is ${results.changed}`);
    while(results.resultSet.goToNextRow()) {
      const row = results.resultSet.getRow();
      console.info(`transUpdateWithReturningSyncExample, name is ${row['NAME']}, age is ${row['AGE']}`);
    }
  } catch (e) {
    console.error(`transUpdateWithReturningSyncExample failed. code is ${e.code}, message is ${e.message}`);
  }
}

delete14+

delete(predicates: RdbPredicates):Promise<number>

Deletes data from the RDB store based on the specified RdbPredicates object. This API uses a promise to return the result.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
predicates RdbPredicates Yes Deletion conditions specified by the RdbPredicates object.

Return value

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

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error.
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.

Example:

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

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      const rows = await transaction.delete(predicates2);
      await transaction.commit();
      console.info(`Delete rows: ${rows}`);
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`Delete failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

deleteSync14+

deleteSync(predicates: RdbPredicates): number

Deletes data from the RDB store based on the specified RdbPredicates object. This API returns the result synchronously.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
predicates RdbPredicates Yes Deletion conditions specified by the RdbPredicates object.

Return value

Type Description
number Number of rows deleted.

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error.
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.

Example:

let predicates3 = new relationalStore.RdbPredicates('EMPLOYEE');
predicates3.equalTo('NAME', 'Lisa');
if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      let rows = transaction.deleteSync(predicates3);
      await transaction.commit();
      console.info(`Delete rows: ${rows}`);
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`Delete failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

deleteWithReturning23+

deleteWithReturning(predicates: RdbPredicates, config: ReturningConfig): Promise<Result>

Deletes data from the RDB store based on the specified RdbPredicates object and returns Result. This API uses a promise to return the result.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Model restriction: This API can be used only in the stage model.

Parameters

Name Type Mandatory Description
predicates RdbPredicates Yes Deletion conditions specified by the RdbPredicates object.
config ReturningConfig Yes Configuration information of the return value.

Return value

Type Description
Promise<Result> Promise used to return the result. If the operation is successful, the affected dataset is returned.

Error codes

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

ID Error Message
14800001 Invalid arguments. Possible causes: 1. Parameter is out of valid range.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800032 SQLite: Abort due to constraint violation.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

Example:

async function transDeleteWithReturningExample(trans: relationalStore.Transaction)
{
  const valueBucket1: relationalStore.ValuesBucket = { 'NAME': 'lisi', 'AGE': 21 };
  const valueBucket2: relationalStore.ValuesBucket = { 'NAME': 'zhangsan', 'AGE': 18 };
  let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
  const config: relationalStore.ReturningConfig = { columns: ['NAME', 'AGE'] };
  try {
    trans.batchInsertWithReturningSync("EMPLOYEE", [valueBucket1, valueBucket2], config);
    let results = await trans.deleteWithReturning(predicates, config);
    console.info(`transDeleteWithReturningExample is successful, changed is ${results.changed}`);
    while(results.resultSet.goToNextRow()) {
      const row = results.resultSet.getRow();
      console.info(`transDeleteWithReturningExample, name is ${row['NAME']}, age is ${row['AGE']}`);
    }
  } catch (e) {
    console.error(`transDeleteWithReturningExample failed. code is ${e.code}, message is ${e.message}`);
  }
}

deleteWithReturningSync23+

deleteWithReturningSync(predicates: RdbPredicates, config: ReturningConfig): Result

Deletes data from the RDB store based on the specified RdbPredicates object and returns Result.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Model restriction: This API can be used only in the stage model.

Parameters

Name Type Mandatory Description
predicates RdbPredicates Yes Deletion conditions specified by the RdbPredicates object.
config ReturningConfig Yes Configuration information of the return value.

Return value

Type Description
Result If the operation is successful, the affected dataset is returned.

Error codes

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

ID Error Message
14800001 Invalid arguments. Possible causes: 1. Parameter is out of valid range.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error. Possible causes: Insert failed or the updated data does not exist.
14800024 SQLite: The database file is locked.
14800025 SQLite: A table in the database is locked.
14800028 SQLite: Some kind of disk I/O error occurred.
14800029 SQLite: The database is full.
14800032 SQLite: Abort due to constraint violation.
14800033 SQLite: Data type mismatch.
14800047 The WAL file size exceeds the default limit.

Example:

function transDeleteWithReturningSyncExample(trans: relationalStore.Transaction)
{
  const valueBucket1: relationalStore.ValuesBucket = { 'NAME': 'lisi', 'AGE': 21 };
  const valueBucket2: relationalStore.ValuesBucket = { 'NAME': 'zhangsan', 'AGE': 18 };
  let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
  const config: relationalStore.ReturningConfig = { columns: ['NAME', 'AGE'] };
  try {
    trans.batchInsertWithReturningSync("EMPLOYEE", [valueBucket1, valueBucket2], config);
    let results = trans.deleteWithReturningSync(predicates, config);
    console.info(`transDeleteWithReturningSyncExample is successful, changed is ${results.changed}`);
    while(results.resultSet.goToNextRow()) {
      const row = results.resultSet.getRow();
      console.info(`transDeleteWithReturningSyncExample, name is ${row['NAME']}, age is ${row['AGE']}`);
    }
  } catch (e) {
    console.error(`transDeleteWithReturningSyncExample failed. code is ${e.code}, message is ${e.message}`);
  }
}

query14+

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

Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
predicates RdbPredicates Yes Query conditions specified by the RdbPredicates object.
columns Array<string> No Columns to query. If null is passed in, all columns are queried.

Return value

Type Description
Promise<ResultSet> Promise used to return the result. If the operation is successful, a ResultSet object will be returned.

Error codes

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

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error.
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.

Example:

let predicates4 = new relationalStore.RdbPredicates('EMPLOYEE');
predicates4.equalTo('NAME', 'Rose');

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      const resultSet = await transaction.query(predicates4, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES']);
      console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
      // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 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}`);
      }
      // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
      resultSet.close();
      await transaction.commit();
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`Query failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

querySync14+

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

Queries data in a database based on specified conditions. This API returns the result synchronously. If complex logic and a large number of loops are involved in the operations on the resultSet obtained by querySync, the freeze problem may occur. You are advised to perform this operation in the taskpool thread.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
predicates RdbPredicates Yes Query conditions specified by the RdbPredicates object.
columns Array<string> No Columns to query. If null is passed in, all columns are queried. The default value is null.

Return value

Type Description
ResultSet If the operation is successful, a ResultSet object will be returned.

Error codes

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

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error.
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.

Example:

let predicates5 = new relationalStore.RdbPredicates('EMPLOYEE');
predicates5.equalTo('NAME', 'Rose');

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      let resultSet = transaction.querySync(predicates5, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES']);
      console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
      // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 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}`);
      }
      // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
      resultSet.close();
      await transaction.commit();
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`Query failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

querySql14+

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

Queries data in the RDB store using the specified SQL statement. The number of relational operators between expressions and operators in the SQL statement cannot exceed 1,000. This API uses a promise to return the result.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
sql string Yes SQL statement to run.
args Array<ValueType> No Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.

Return value

Type Description
Promise<ResultSet> Promise used to return the result. If the operation is successful, a ResultSet object will be returned.

Error codes

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

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error.
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.

Example:

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      const resultSet = await transaction.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'");
      console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
      // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 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}`);
      }
      // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
      resultSet.close();
      await transaction.commit();
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`Query failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

querySqlSync14+

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

Queries data in the RDB store using the specified SQL statement. The number of relational operators between expressions and operators in the SQL statement cannot exceed 1,000. If complex logic and a large number of loops are involved in the operations on the resultSet obtained by querySync, the freeze problem may occur. You are advised to perform this operation in the taskpool thread.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
sql string Yes SQL statement to run.
args Array<ValueType> No Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank. The default value is null.

Return value

Type Description
ResultSet If the operation is successful, a ResultSet object will be returned.

Error codes

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

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance is already closed.
14800021 SQLite: Generic error.
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.

Example:

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      let resultSet = transaction.querySqlSync("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = 'sanguo'");
      console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
      // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 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}`);
      }
      // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
      resultSet.close();
      await transaction.commit();
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`Query failed, code is ${err.code},message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

queryWithoutRowCount23+

queryWithoutRowCount(predicates: RdbPredicates, columns?: Array<string>): Promise<LiteResultSet>

Queries data from the RDB store based on specified conditions without calculating the row count. This API delivers better performance than the query API. This API uses a promise to return the result.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Model restriction: This API can be used only in the stage model.

Parameters

Name Type Mandatory Description
predicates RdbPredicates Yes Query conditions specified by the RdbPredicates object.
columns Array<string> No Columns to query. If null is passed in, all columns are queried. The default value is null.

Return value

Type Description
Promise<LiteResultSet> If the operation is successful, a LiteResultSet object will be returned.

Error codes

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

ID Error Message
14800014 The target instance is already closed.

Example:

async function queryWithoutRowCountExample(store : relationalStore.RdbStore) {
  let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
  predicates.equalTo("NAME", "Rose");
  if (store != undefined) {
    try {
      const transaction = await store.createTransaction();
      let resultSet: relationalStore.LiteResultSet | undefined;
      try {
        resultSet = await transaction.queryWithoutRowCount(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
        if (resultSet != undefined) {
          // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 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}`);
          }
          // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
          resultSet.close();
        }
        await transaction.commit();
      } catch (err) {
        console.error(`Query failed, code is ${err.code}, message is ${err.message}`);
        // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
        if (resultSet != undefined) {
          resultSet.close();
        }
        await transaction.rollback();
      }
    } catch (err) {
      console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
    }
  }
}

queryWithoutRowCountSync23+

queryWithoutRowCountSync(predicates: RdbPredicates, columns?: Array<string>): LiteResultSet

Queries data from the RDB store based on specified conditions without calculating the row count. If complex logic and a large number of loops are involved in the operations on the LiteResultSet obtained by queryWithoutRowCountSync, the freeze problem may occur. You are advised to perform this operation in the taskpool thread.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Model restriction: This API can be used only in the stage model.

Parameters

Name Type Mandatory Description
predicates RdbPredicates Yes Query conditions specified by the RdbPredicates object.
columns Array<string> No Columns to query. If null is passed in, all columns are queried. The default value is null.

Return value

Type Description
LiteResultSet If the operation is successful, a LiteResultSet object will be returned.

Error codes

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

ID Error Message
14800014 The target instance is already closed.

Example:

async function queryWithoutRowCountSyncExample(store : relationalStore.RdbStore) {
  let predicates = new relationalStore.RdbPredicates("EMPLOYEE");
  predicates.equalTo("NAME", "Rose");
  if (store != undefined) {
    try {
      const transaction = await store.createTransaction();
      let resultSet: relationalStore.LiteResultSet | undefined;
      try {
        resultSet = transaction.queryWithoutRowCountSync(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
        if (resultSet != undefined) {
          // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 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}`);
          }
          // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
          resultSet.close();
        }
        await transaction.commit();
      } catch (err) {
        console.error(`Query failed, code is ${err.code}, message is ${err.message}`);
        // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
        if (resultSet != undefined) {
          resultSet.close();
        }
        await transaction.rollback();
      }
    } catch (err) {
      console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
    }
  }
}

querySqlWithoutRowCount23+

querySqlWithoutRowCount(sql: string, bindArgs?: Array<ValueType>): Promise<LiteResultSet>

Queries data from the RDB store based on specified conditions without calculating the row count. This API uses a promise to return the result and delivers better performance than the querySql API. The number of relational operators between expressions and operators in the SQL statement cannot exceed 1,000.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
sql string Yes SQL statement to run.
bindArgs Array<ValueType> No Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.

Return value

Type Description
Promise<LiteResultSet> Promise used to return the result. If the operation is successful, a LiteResultSet object will be returned.

Error codes

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

ID Error Message
14800001 Invalid arguments. Possible causes: 1.Parameter is out of valid range.
14800014 The target instance is already closed.

Example:

async function querySqlWithoutRowCountExample(store : relationalStore.RdbStore) {
  if (store != undefined) {
    try {
    const transaction = await store.createTransaction();
    let resultSet: relationalStore.LiteResultSet | undefined;
      try {
        resultSet = await transaction.querySqlWithoutRowCount('select * from EMPLOYEE where name = ?', ["Rose"]);
        if (resultSet != undefined) {
          // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 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}`);
          }
          // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
          resultSet.close();
        }
        await transaction.commit();
      } catch (err) {
        console.error(`Query failed, code is ${err.code}, message is ${err.message}`);
        // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
        if (resultSet != undefined) {
          resultSet.close();
        }
        await transaction.rollback();
      }
    } catch (err) {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
    }
  }
}

querySqlWithoutRowCountSync23+

querySqlWithoutRowCountSync(sql: string, bindArgs?: Array<ValueType>):LiteResultSet

Queries data from the RDB store based on specified SQL statements without calculating the row count. The number of relational operators between expressions and operators in the SQL statement cannot exceed 1,000. If complex logic and a large number of loops are involved in the operations on the LiteResultSet obtained by querySqlWithoutRowCountSync, the freeze problem may occur. You are advised to perform this operation in the taskpool thread.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
sql string Yes SQL statement to run.
bindArgs Array<ValueType> No Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank. The default value is null.

Return value

Type Description
LiteResultSet If the operation is successful, a LiteResultSet object will be returned.

Error codes

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

ID Error Message
14800001 Invalid arguments. Possible causes: 1.Parameter is out of valid range.
14800014 The target instance is already closed.

Example:

async function querySqlWithoutRowCountSyncExample(store : relationalStore.RdbStore) {
  if (store != undefined) {
    try {
    const transaction = await store.createTransaction();
    let resultSet: relationalStore.LiteResultSet | undefined;
      try {
        resultSet = transaction.querySqlWithoutRowCountSync('select * from EMPLOYEE where name = ?', ["Rose"]);
        if (resultSet != undefined) {
          // resultSet is a cursor of a data set. By default, the cursor points to the -1st record. Valid data starts from 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}`);
          }
          // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
          resultSet.close();
        }
        await transaction.commit();
      } catch (err) {
        console.error(`Query failed, code is ${err.code}, message is ${err.message}`);
        // Release the memory of resultSet. If the memory is not released, FD or memory leaks may occur.
        if (resultSet != undefined) {
          resultSet.close();
        }
        await transaction.rollback();
      }
    } catch (err) {
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
    }
  }
}

execute14+

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

Executes an SQL statement that contains specified arguments. The number of relational operators between expressions and operators in the statement cannot exceed 1,000. This API uses a promise to return a value of the ValueType type.

This API can be used to add, delete, and modify data, run SQL statements of the PRAGMA syntax, and create, delete, and modify a table. The type of the return value varies, depending on the execution result.

This API does not support query, database attachment, and transaction operations. You can use querySql or query to query data, and use attach to attach a database.

Statements separated by semicolons (;) are not supported.

Statements starting with comments are not supported.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
sql string Yes SQL statement to run.
args Array<ValueType> No Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.

Return value

Type Description
Promise<ValueType> Promise used to return the SQL execution result.

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported the sql(attach,begin,commit,rollback etc.).
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      // Delete all data from the table.
      const SQL_DELETE_TABLE = 'DELETE FROM EMPLOYEE';
      const data = await transaction.execute(SQL_DELETE_TABLE);
      await transaction.commit();
      console.info(`delete result: ${data}`);
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`delete failed, code is ${err.code}, message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}

executeSync14+

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

Executes an SQL statement that contains specified arguments. The number of relational operators between expressions and operators in the statement cannot exceed 1,000. This API returns a value of the ValueType type.

This API can be used to add, delete, and modify data, run SQL statements of the PRAGMA syntax, and create, delete, and modify a table. The type of the return value varies, depending on the execution result.

This API does not support query, database attachment, and transaction operations. You can use querySql or query to query data, and use attach to attach a database.

Statements separated by semicolons (;) are not supported.

Statements starting with comments are not supported.

System capability: SystemCapability.DistributedDataManager.RelationalStore.Core

Parameters

Name Type Mandatory Description
sql string Yes SQL statement to run.
args Array<ValueType> No Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If this parameter is left blank or set to null or undefined, the SQL statement is complete. The default value is null.

Return value

Type Description
ValueType SQL execution result.

Error codes

For details about the error codes, see Universal Error Codes and RDB Store Error Codes. For details about how to handle error 14800011, see Database Backup and Restore.

ID Error Message
401 Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed.
801 Capability not supported the sql(attach,begin,commit,rollback etc.).
14800000 Inner error.
14800011 The current operation failed because the database is corrupted.
14800014 The target instance 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.

Example:

// Delete all data from the table.
if (store != undefined) {
  try {
    const transaction = await store.createTransaction();
    try {
      const SQL_DELETE_TABLE = 'DELETE FROM EMPLOYEE';
      let data = transaction.executeSync(SQL_DELETE_TABLE);
      await transaction.commit();
      console.info(`delete result: ${data}`);
    } catch (error) {
      const err = error as BusinessError;
      await transaction.rollback();
      console.error(`delete failed, code is ${err.code}, message is ${err.message}`);
    }
  } catch (error) {
    const err = error as BusinessError;
    console.error(`createTransaction failed, code is ${err.code},message is ${err.message}`);
  }
}