diff --git a/arkuix/js-apis-data-preferences.md b/arkuix/js-apis-data-preferences.md new file mode 100644 index 0000000000000000000000000000000000000000..9bcefa50dc64d6743fb7d83952cc314e5d0123d4 --- /dev/null +++ b/arkuix/js-apis-data-preferences.md @@ -0,0 +1,1741 @@ +# @ohos.data.preferences (User Preferences) + +The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs, and supports persistence of the KV pairs when required, as well as modification and query of the data. + +The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values. + + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +```ts +import data_preferences from '@ohos.data.preferences'; +``` + +## Constants + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +| Name | Type| Readable| Writable| Description | +| ---------------- | -------- | ---- | ---- | --------------------------------------- | +| MAX_KEY_LENGTH | number | Yes | No | Maximum length of a key, which is 80 bytes. | +| MAX_VALUE_LENGTH | number | Yes | No | Maximum length of a value, which is 8192 bytes.| + + +## data_preferences.getPreferences + +getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void + +Obtains a **Preferences** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md). | +| name | string | Yes | Name of the **Preferences** instance. | +| callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and the **Preferences** instance obtained is returned. Otherwise, **err** is an error object.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences | null = null; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => { + if (err) { + console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + return; + } + preferences = val; + console.info("Succeeded in getting preferences."); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.getPreferences + +getPreferences(context: Context, name: string): Promise<Preferences> + +Obtains a **Preferences** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md). | +| name | string | Yes | Name of the **Preferences** instance.| + +**Return value** + +| Type | Description | +| ------------------------------------------ | ---------------------------------- | +| Promise<[Preferences](#preferences)> | Promise used to return the **Preferences** instance obtained.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences | null = null; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let promise = data_preferences.getPreferences(this.context, 'myStore'); + promise.then((object: data_preferences.Preferences) => { + preferences = object; + console.info("Succeeded in getting preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.getPreferences10+ + +getPreferences(context: Context, options: Options, callback: AsyncCallback<Preferences>): void + +Obtains a **Preferences** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | +| callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and the **Preferences** instance obtained is returned. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). + +| ID| Error Message | +| -------- | ------------------------------ | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences | null = null; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => { + if (err) { + console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + return; + } + preferences = val; + console.info("Succeeded in getting preferences."); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.getPreferences10+ + +getPreferences(context: Context, options: Options): Promise<Preferences> + +Obtains a **Preferences** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | + +**Return value** + +| Type | Description | +| --------------------------------------- | ---------------------------------- | +| Promise<[Preferences](#preferences)> | Promise used to return the **Preferences** instance obtained.| + +**Error codes** + +For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). + +| ID| Error Message | +| -------- | ------------------------------ | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences | null = null; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.getPreferences(this.context, options); + promise.then((object: data_preferences.Preferences) => { + preferences = object; + console.info("Succeeded in getting preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.getPreferencesSync10+ + +getPreferencesSync(context: Context, options: Options): Preferences + +Obtains the **Preferences** instance. This API is a synchronous interface. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | + +**Return value** + +| Type | Description | +| --------------------------- | --------------------- | +| [Preferences](#preferences) | **Preferences** instance obtained.| + +**Error codes** + +For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences | null = null; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + preferences = data_preferences.getPreferencesSync(this.context, options); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.deletePreferences + +deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void + +Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses an asynchronous callback to return the result. + +After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md). | +| name | string | Yes | Name of the **Preferences** instance. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). + +| ID| Error Message | +| -------- | ------------------------------| +| 15500010 | Failed to delete preferences file. | + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + data_preferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => { + if (err) { + console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in deleting preferences." ); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.deletePreferences + +deletePreferences(context: Context, name: string): Promise<void> + +Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses a promise to return the result. + +After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md). | +| name | string | Yes | Name of the **Preferences** instance.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). + +| ID| Error Message | +| -------- | ------------------------------| +| 15500010 | Failed to delete preferences file. | + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try{ + let promise = data_preferences.deletePreferences(this.context, 'myStore'); + promise.then(() => { + console.info("Succeeded in deleting preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.deletePreferences10+ + +deletePreferences(context: Context, options: Options, callback: AsyncCallback<void>): void + +Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses an asynchronous callback to return the result. + +After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). + +| ID| Error Message | +| -------- | ---------------------------------- | +| 15500010 | Failed to delete preferences file. | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.deletePreferences(this.context, options, (err: BusinessError) => { + if (err) { + console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in deleting preferences." ); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.deletePreferences10+ + +deletePreferences(context: Context, options: Options): Promise<void> + +Deletes a **Preferences** instance from the cache. If the **Preferences** instance has a persistent file, the persistent file will also be deleted. This API uses a promise to return the result. + +After the **Preferences** instance is deleted, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the deleted **Preferences** instance to null. The system will reclaim the deleted **Preferences** instances in a unified manner. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). + +| ID| Error Message | +| -------- | ---------------------------------- | +| 15500010 | Failed to delete preferences file. | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try{ + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.deletePreferences(this.context, options); + promise.then(() => { + console.info("Succeeded in deleting preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.removePreferencesFromCache + +removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback<void>): void + +Removes a **Preferences** instance from the cache. This API uses an asynchronous callback to return the result. + +After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. + +After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md). | +| name | string | Yes | Name of the **Preferences** instance. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + data_preferences.removePreferencesFromCache(this.context, 'myStore', (err: BusinessError) => { + if (err) { + console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in removing preferences."); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} + +``` + +## data_preferences.removePreferencesFromCache + +removePreferencesFromCache(context: Context, name: string): Promise<void> + +Removes a **Preferences** instance from the cache. This API uses a promise to return the result. + +After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. + +After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md). | +| name | string | Yes | Name of the **Preferences** instance.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let promise = data_preferences.removePreferencesFromCache(this.context, 'myStore'); + promise.then(() => { + console.info("Succeeded in removing preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.removePreferencesFromCacheSync10+ + +removePreferencesFromCacheSync(context: Context, name: string): void + +Removes a **Preferences** instance from the cache. This API returns the result synchronously. + +After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. + +After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md). | +| name | string | Yes | Name of the **Preferences** instance.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + data_preferences.removePreferencesFromCacheSync(this.context, 'myStore'); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.removePreferencesFromCache10+ + +removePreferencesFromCache(context: Context, options: Options, callback: AsyncCallback<void>): void + +Removes a **Preferences** instance from the cache. This API uses an asynchronous callback to return the result. + +After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. + +After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). + +| ID| Error Message | +| -------- | ------------------------------ | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => { + if (err) { + console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in removing preferences."); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.removePreferencesFromCache10+ + +removePreferencesFromCache(context: Context, options: Options): Promise<void> + +Removes a **Preferences** instance from the cache. This API uses a promise to return the result. + +After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. + +After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). + +| ID| Error Message | +| -------- | ------------------------------ | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.removePreferencesFromCache(this.context, options); + promise.then(() => { + console.info("Succeeded in removing preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.removePreferencesFromCacheSync10+ + +removePreferencesFromCacheSync(context: Context, options: Options):void + +Removes a **Preferences** instance from the cache. This API returns the result synchronously. + +After an application calls [getPreferences](#data_preferencesgetpreferences) for the first time to obtain a **Preferences** instance, the obtained **Preferences** instance is cached. When the application calls [getPreferences](#data_preferencesgetpreferences) again, the **Preferences** instance will be read from the cache instead of from the persistent file. After this API is called to remove the instance from the cache, calling **getPreferences** again will read data from the persistent file and create a new **Preferences** instance. + +After the **Preferences** instance is removed, do not use it to perform data operations. Otherwise, data inconsistency may be caused. For this purpose, set the removed **Preferences** instance to null. The system will reclaim the removed **Preferences** instances in a unified manner. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| options | [Options](#options10) | Yes | Configuration options of the **Preferences** instance. | + +**Error codes** + +For details about the error codes, see [User Preference Error Codes](../errorcodes/errorcode-preferences.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.removePreferencesFromCacheSync(this.context, options); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## Options10+ + +Represents the configuration options of a **Preferences** instance. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the **Preferences** instance. | +| dataGroupId | string | No | Application group ID, which needs to be obtained from the AppGallery.
**Model restriction**: This attribute can be used only in the stage model.
This parameter is supported since API version 10. It specifies the **Preferences** instance created in the sandbox directory corresponding to the **dataGroupId**. If this parameter is not specified, the **Preferences** instance is created in the sandbox directory of the application.| + +## Preferences + +Provides APIs for obtaining and modifying the stored data. + +Before calling any method of **Preferences**, you must obtain a **Preferences** instance by using [data_preferences.getPreferences](#data_preferencesgetpreferences). + + +### get + +get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void + +Obtains the value corresponding to the specified key from the cached **Preferences** instance. This API uses an asynchronous callback to return the result. If the value is null or is not of the default value type, **defValue** is returned. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data to obtain. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| +| callback | AsyncCallback<[ValueType](#valuetype)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the value obtained. Otherwise, **err** is an error object.| + +**Example** + +```ts +try { + preferences.get('startup', 'default', (err: BusinessError, val: data_preferences.ValueType) => { + if (err) { + console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Obtained the value of 'startup' successfully. val: " + val); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); +} +``` + +### get + +get(key: string, defValue: ValueType): Promise<ValueType> + +Obtains the value corresponding to the specified key from the cached **Preferences** instance. This API uses a promise to return the result. If the value is null or is not of the default value type, **defValue** is returned. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + + **Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data to obtain. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| + +**Return value** + +| Type | Description | +| ----------------------------------- | ----------------------------- | +| Promise<[ValueType](#valuetype)> | Promise used to return the value obtained.| + +**Example** + +```ts +try { + let promise = preferences.get('startup', 'default'); + promise.then((data: data_preferences.ValueType) => { + console.info("Got the value of 'startup'. Data: " + data); + }).catch((err: BusinessError) => { + console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); +} +``` + +### getSync10+ + +getSync(key: string, defValue: ValueType): ValueType + +Obtains the value corresponding to the specified key from the cached **Preferences** instance. This API returns the result synchronously. If the value is null or is not of the default value type, **defValue** is returned. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data to obtain. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| + +**Return value** + +| Type | Description | +| ----------------------------------- | ----------------------------- | +| [ValueType](#valuetype) | Returns the value obtained.| + +**Example** + +```ts +try { + let value: data_preferences.ValueType = preferences.getSync('startup', 'default'); + console.info("Succeeded in getting value of 'startup'. Data: " + value); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); +} +``` + +### getAll + +getAll(callback: AsyncCallback<Object>): void; + +Obtains all KV pairs from the cached **Preferences** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<Object> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **value** provides all KV pairs obtained. Otherwise, **err** is an error object.| + +**Example** + +```ts +// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used. +// If an error is reported, extract this API to a .ts file and expose it. Then import the API to the .ets file when required. +function getObjKeys(obj: Object): string[] { + let keys = Object.keys(obj); + return keys; +} + +try { + preferences.getAll((err: BusinessError, value: Object) => { + if (err) { + console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); + return; + } + let allKeys = getObjKeys(value); + console.info("getAll keys = " + allKeys); + console.info("getAll object = " + JSON.stringify(value)); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get all key-values. code =" + code + ", message =" + message); +} +``` + +### getAll + +getAll(): Promise<Object> + +Obtains all KV pairs from the cached **Preferences** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------- | +| Promise<Object> | Promise used to return the KV pairs obtained.| + +**Example** + +```ts +// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used. +// If an error is reported, extract this API to a .ts file and expose it. Then import the API to the .ets file when required. +function getObjKeys(obj: Object): string[] { + let keys = Object.keys(obj); + return keys; +} + +try { + let promise = preferences.getAll(); + promise.then((value: Object) => { + let allKeys = getObjKeys(value); + console.info('getAll keys = ' + allKeys); + console.info("getAll object = " + JSON.stringify(value)); + }).catch((err: BusinessError) => { + console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get all key-values. code =" + code + ", message =" + message); +} +``` + +### getAllSync10+ + +getAllSync(): Object + +Obtains all KV pairs from the cached **Preferences** instance. This API returns the result synchronously. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------- | +| Object | Returns all KV pairs obtained.| + +**Example** + +```ts +// There is no Object.keys in ArkTS, and the for..in... syntax cannot be used. +// If an error is reported, extract this API to a .ts file and expose it. Then import the API to the .ets file when required. +function getObjKeys(obj: Object): string[] { + let keys = Object.keys(obj); + return keys; +} + +try { + let value = preferences.getAllSync(); + let allKeys = getObjKeys(value); + console.info('getAll keys = ' + allKeys); + console.info("getAll object = " + JSON.stringify(value)); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get all key-values. code =" + code + ", message =" + message); +} +``` + +### put + +put(key: string, value: ValueType, callback: AsyncCallback<void>): void + +Writes data to the cached **Preferences** instance. This API uses an asynchronous callback to return the result. You can use [flush](#flush) to persist the **Preferences** instance. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If data is written successfully, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Example** + +```ts +try { + preferences.put('startup', 'auto', (err: BusinessError) => { + if (err) { + console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Successfully put the value of 'startup'."); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to put value of 'startup'. code =" + code + ", message =" + message); +} +``` + + +### put + +put(key: string, value: ValueType): Promise<void> + +Writes data to the cached **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +try { + let promise = preferences.put('startup', 'auto'); + promise.then(() => { + console.info("Successfully put the value of 'startup'."); + }).catch((err: BusinessError) => { + console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to put value of 'startup'. code =" + code +", message =" + message); +} +``` + + +### putSync10+ + +putSync(key: string, value: ValueType): void + +Writes data to the cached **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| + +**Example** + +```ts +try { + preferences.putSync('startup', 'auto'); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to put value of 'startup'. code =" + code +", message =" + message); +} +``` + + +### has + +has(key: string, callback: AsyncCallback<boolean>): void + +Checks whether the cached **Preferences** instance contains the KV pair of the given key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data to check. It cannot be empty. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| + +**Example** + +```ts +try { + preferences.has('startup', (err: BusinessError, val: boolean) => { + if (err) { + console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); + return; + } + if (val) { + console.info("The key 'startup' is contained."); + } else { + console.info("The key 'startup' is not contained."); + } + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); +} +``` + + +### has + +has(key: string): Promise<boolean> + +Checks whether the cached **Preferences** instance contains the KV pair of the given key. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------- | +| key | string | Yes | Key of the data to check. It cannot be empty.| + +**Return value** + +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| + +**Example** + +```ts +try { + let promise = preferences.has('startup'); + promise.then((val: boolean) => { + if (val) { + console.info("The key 'startup' is contained."); + } else { + console.info("The key 'startup' is not contained."); + } + }).catch((err: BusinessError) => { + console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); +} +``` + + +### hasSync10+ + +hasSync(key: string): boolean + +Checks whether the cached **Preferences** instance contains the KV pair of the given key. This API returns the result synchronously. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------- | +| key | string | Yes | Key of the data to check. It cannot be empty.| + +**Return value** + +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| boolean | If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| + +**Example** + +```ts +try { + let isExist: boolean = preferences.hasSync('startup'); + if (isExist) { + console.info("The key 'startup' is contained."); + } else { + console.info("The key 'startup' is not contained."); + } +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); +} +``` + + +### delete + +delete(key: string, callback: AsyncCallback<void>): void + +Deletes the KV pair from the cached **Preferences** instance based on the specified key. This API uses an asynchronous callback to return the result. You can use [flush](#flush) to persist the **Preferences** instance. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```ts +try { + preferences.delete('startup', (err: BusinessError) => { + if (err) { + console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Deleted the key 'startup'."); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete the key 'startup'. code =" + code + ", message =" + message); +} +``` + + +### delete + +delete(key: string): Promise<void> + +Deletes a KV pair from the cached **Preferences** instance based on the specified key. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------- | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +try { + let promise = preferences.delete('startup'); + promise.then(() => { + console.info("Deleted the key 'startup'."); + }).catch((err: BusinessError) => { + console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message); +} +``` + + +### deleteSync10+ + +deleteSync(key: string): void + +Deletes a KV pair from the cached **Preferences** instance based on the specified key. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------- | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty.| + +**Example** + +```ts +try { + preferences.deleteSync('startup'); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message); +} +``` + + +### flush + +flush(callback: AsyncCallback<void>): void + +Flushes the data in the cached **Preferences** instance to the persistent file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```ts +try { + preferences.flush((err: BusinessError) => { + if (err) { + console.error("Failed to flush. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Successfully flushed data."); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); +} +``` + + +### flush + +flush(): Promise<void> + +Flushes the data in the cached **Preferences** instance to the persistent file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +try { + let promise = preferences.flush(); + promise.then(() => { + console.info("Successfully flushed data."); + }).catch((err: BusinessError) => { + console.error("Failed to flush. code =" + err.code + ", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); +} +``` + + +### clear + +clear(callback: AsyncCallback<void>): void + +Clears all data in the cached **Preferences** instance. This API uses an asynchronous callback to return the result. You can use [flush](#flush) to persist the **Preferences** instance. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```ts +try { + preferences.clear((err: BusinessError) =>{ + if (err) { + console.error("Failed to clear. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Successfully cleared data."); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to clear. code =" + code + ", message =" + message); +} +``` + + +### clear + +clear(): Promise<void> + +Clears all data in the cached **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to persist the **Preferences** instance. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +try { + let promise = preferences.clear(); + promise.then(() => { + console.info("Successfully cleared data."); + }).catch((err: BusinessError) => { + console.error("Failed to clear. code =" + err.code + ", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to clear. code =" + code + ", message =" + message); +} +``` + + +### clearSync10+ + +clearSync(): void + +Clears all data in the cached **Preferences** instance. This API returns the result synchronously. You can use [flush](#flush) to persist the **Preferences** instance. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Example** + +```ts +try { + preferences.clearSync(); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to clear. code =" + code + ", message =" + message); +} +``` + + +### on('change') + +on(type: 'change', callback: ( key : string ) => void): void + +Subscribes to data changes. A callback will be triggered to return the new value if the value of the subscribed key is changed and [flushed](#flush). + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. The value is **change**, which indicates data changes.| +| callback | Function | Yes | Callback invoked to return the data change.
**key** indicates the key whose value is changed. | + +**Example** + +```ts +try { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: data_preferences.Preferences) => { + if (err) { + console.error("Failed to get preferences."); + return; + } + preferences.on('change', (key: string) => { + console.info("The key " + key + " changed."); + }); + preferences.put('startup', 'manual', (err: BusinessError) => { + if (err) { + console.error("Failed to put the value of 'startup'. Cause: " + err); + return; + } + console.info("Successfully put the value of 'startup'."); + + preferences.flush((err: BusinessError) => { + if (err) { + console.error("Failed to flush. Cause: " + err); + return; + } + console.info("Successfully flushed data."); + }) + }) + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); +} +``` + +### off('change') + +off(type: 'change', callback?: ( key : string ) => void): void + +Unsubscribes from data changes. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is **change**, which indicates data changes. | +| callback | Function | No | Callback to unregister. If this parameter is left blank, all callbacks for data changes will be unregistered.
**key** indicates the key whose value is changed.| + +**Example** + +```ts + +try { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: data_preferences.Preferences) => { + if (err) { + console.error("Failed to get preferences."); + return; + } + preferences.on('change', (key: string) => { + console.info("The key " + key + " changed."); + }); + preferences.put('startup', 'auto', (err: BusinessError) => { + if (err) { + console.error("Failed to put the value of 'startup'. Cause: " + err); + return; + } + console.info("Successfully put the value of 'startup'."); + + preferences.flush((err: BusinessError) =>{ + if (err) { + console.error("Failed to flush. Cause: " + err); + return; + } + console.info("Successfully flushed data."); + }) + preferences.off('change', (key: string) => { + console.info("The key " + key + " changed."); + }); + }) + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); +} +``` + +### on('dataChange')20+ + +on(type: 'dataChange', keys: Array<string>, callback: Callback<Record<string, ValueType>>): void + +Subscribes to changes of specific data. The registered callback will be invoked only after the values of the specified keys are changed and [flushed](#flush). + + > **NOTE** + > + > After [removePreferencesFromCache](#preferencesremovepreferencesfromcache) or [deletePreferences](#preferencesdeletepreferences) is called, the data change subscription will be automatically canceled. After [getPreferences](#preferencesgetpreferences) is called again, you need to subscribe to data changes again. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is **'dataChange'**, which indicates data changes. | +| keys | Array<string> | Yes | Array of the keys to be observed. | +| callback | Callback<Record<string, [ValueType](#valuetype)>> | Yes | Callback used to return the changed data, in an array of KV pairs. The keys identify the data changed, and the values are the new values. The values support the following data types: number, string, boolean, Array\, Array\, Array\< boolean>, Uint8Array, and object.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). + +| ID| Error Message | +| -------- | ------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | +| 15500000 | Inner error. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +let observer = (data: Record) => { + for (const keyValue of Object.entries(data)) { + console.info(`observer : ${keyValue}`); + } + console.info("The observer called."); +} +let keys = ['name', 'age']; +dataPreferences.on('dataChange', keys, observer); +dataPreferences.putSync('name', 'xiaohong'); +dataPreferences.putSync('weight', 125); +dataPreferences.flush((err: BusinessError) => { + if (err) { + console.error("Failed to flush. Cause: " + err); + return; + } + console.info("Successfully flushed data."); +}) +``` + +### off('dataChange')20+ + +off(type: 'dataChange', keys: Array<string>, callback?: Callback<Record<string, ValueType>>): void + +Unsubscribes from changes of specific data. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is **'dataChange'**, which indicates data changes. | +| keys | Array<string> | Yes | Array of keys to be unsubscribed from. If this parameter is left empty, all keys are unsubscribed from.| +| callback | Callback<Record<string, [ValueType](#valuetype)>> | No | Callback to unregister. If this parameter is not specified, this API unregisters all callbacks for the changes of the specified data.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [User Preference Error Codes](errorcode-preferences.md). + +| ID| Error Message | +| -------- | ------------------------------ | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | +| 15500000 | Inner error. | + +**Example** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +let observer = (data: Record) => { + for (const keyValue of Object.entries(data)) { + console.info(`observer : ${keyValue}`); + } + console.info("The observer called."); +} +let keys = ['name', 'age']; +dataPreferences.on('dataChange', keys, observer); +dataPreferences.putSync('name', 'xiaohong'); +dataPreferences.putSync('weight', 125); +dataPreferences.flush((err: BusinessError) => { + if (err) { + console.error("Failed to flush. Cause: " + err); + return; + } + console.info("Successfully flushed data."); +}) +dataPreferences.off('dataChange', keys, observer); +``` + +## ValueType + +Enumerates the value types. + +**System capability**: SystemCapability.DistributedDataManager.Preferences.Core + +| Type | Description | +| --------------- | ------------------------------ | +| number | The value is a number. | +| string | The value is a string. | +| boolean | The value is of Boolean type. | +| Array\ | The value is an array of numbers. | +| Array\ | The value is a Boolean array. | +| Array\ | The value is an array of strings.| diff --git a/arkuix/js-apis-data-relationalStore.md b/arkuix/js-apis-data-relationalStore.md new file mode 100644 index 0000000000000000000000000000000000000000..de7ab8d7c9c63aaece29c83ac2d424f509b5b5c7 --- /dev/null +++ b/arkuix/js-apis-data-relationalStore.md @@ -0,0 +1,5232 @@ +# @ohos.data.relationalStore (RDB Store) + +The relational database (RDB) store manages data based on relational models. The RDB store provides a complete mechanism for managing local databases based on the underlying SQLite. To satisfy different needs in complicated scenarios, the RDB store offers a series of APIs for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. The worker threads are not supported. + +The **relationalStore** module provides the following functions: + +- [RdbPredicates](#rdbpredicates): provides predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. +- [RdbStore](#rdbstore): provides APIs for managing data in an RDB store. +- [Resultset](#resultset): provides APIs for accessing the result set obtained from the RDB store. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import relationalStore from '@ohos.data.relationalStore'; +``` + +## relationalStore.getRdbStore + +getRdbStore(context: Context, config: StoreConfig, callback: AsyncCallback<RdbStore>): void + +Obtains an RDB store. This API uses an asynchronous callback to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes | Callback invoked to return the RDB store obtained. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800011 | Failed to open database by database corrupted. | +| 14800000 | Inner error. | + +Stage model: + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; + +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> + +Obtains an RDB store. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | + +**Return value** + +| Type | Description | +| ----------------------------------------- | --------------------------------- | +| Promise<[RdbStore](#rdbstore)> | Promise used to return the **RdbStore** object.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800011 | Failed to open database by database corrupted. | +| 14800000 | Inner error. | + +Stage model: + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + let store: relationalStore.RdbStore; + 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 + +Deletes an RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| name | string | Yes | Name of the RDB store to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800000 | Inner error. | + +Stage model: + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; + +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> + +Deletes an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| name | string | Yes | Name of the RDB store to delete. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800000 | Inner error. | + +Stage model: + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; + +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 + +Deletes an RDB store. This API uses an asynchronous callback to return the result. + +After the deletion, you are advised to set the database object to null. If the database file is in the public sandbox directory, you must use this API to delete the database. If the database is accessed by multiple processes at the same time, you are advised to send a database deletion notification to other processes. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | 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. | + +**Example** + +Stage model: + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; + +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\ + +Deletes an RDB store. This API uses a promise to return the result. + +After the deletion, you are advised to set the database object to null. If the database file is in the public sandbox directory, you must use this API to delete the database. If the database is accessed by multiple processes at the same time, you are advised to send a database deletion notification to other processes. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the stage model, see [Context](js-apis-inner-application-uiAbilityContext.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | 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. | + +**Example** + +Stage model: + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; +import { BusinessError } from "@ohos.base"; + +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 + +Defines the RDB store configuration. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------- | ------------- | ---- | --------------------------------------------------------- | +| name | string | Yes | Database file name. | +| securityLevel | [SecurityLevel](#securitylevel) | Yes | Security level of the RDB store. | +| encrypt | boolean | No | Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store; the value **false** (default) means the opposite.
If this parameter is set to true, the cryptoParam parameter must also be configured to set the encrypted database key.| +| dataGroupId10+ | string | No| Application group ID, which needs to be obtained from the AppGallery.
**Model restriction**: This attribute can be used only in the stage model.
This parameter is supported since API version 10. It specifies the **relationalStore** instance created in the sandbox directory corresponding to the **dataGroupId**. If this parameter is not specified, the **relationalStore** instance is created in the sandbox directory of the application.| +| isReadOnly20+ | boolean | No| Whether the RDB store is read-only.
**true**: The RDB store is read-only. Writing data to the RDB store will result in error code 801.
**false** (default): The RDB store is readable and writeable.
This parameter is supported since API version 12.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| rootDir20+ | string | No| Root path of the database.
This parameter is supported since API version 18. The database in the **rootDir** + "/" + **customDir** directory will be opened or deleted. The database opened is read-only. Writing data to a read-only database will trigger error 801. If this parameter is set when you want to open or delete an RDB store, ensure that the database file exists in the corresponding path and the caller has the read permission. Otherwise, error 14800010 will be returned.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| cryptoParam20+ | [CryptoParam](#cryptoparam14) | No| Custom encryption parameters.
If this parameter is left empty, the default encryption parameters are used. For details, see default values of [CryptoParam](#cryptoparam14).
This parameter is valid only when **encrypt** is **true**.
This parameter is supported since API version 14.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| +| persist20+ | boolean | No| Whether to persist the RDB store. The value **true** means to persist the RDB store; the value **false** means the opposite (using an in-memory database).
Default value: **true**.
An in-memory database does not support encryption, backup, restore, cross-process access, and distributed capabilities, with the **securityLevel** property ignored.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core| + +## SecurityLevel + +Enumerates the RDB store security levels. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Value | Description | +| ---- | ---- | ------------------------------------------------------------ | +| S1 | 1 | The RDB store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, an RDB store that contains system data such as wallpapers.| +| S2 | 2 | The RDB store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, an RDB store that contains information created by users or call records, such as audio or video clips.| +| S3 | 3 | The RDB store security level is high. If data leakage occurs, major impact will be caused on the database. For example, an RDB store that contains information such as user fitness, health, and location data.| +| S4 | 4 | The RDB store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, an RDB store that contains information such as authentication credentials and financial data.| + +## CryptoParam20+ + +Represents the configuration of database encryption parameters. This parameter is valid only when **encrypt** in **StoreConfig** is **true**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------- | ------ | ---- | ------------------------------------------------------------ | +| encryptionKey | Uint8Array | Yes | Key used for database encryption and decryption.
If the key is not required, you need to set the key to 0s.| +| iterationCount | number | No| Number of iterations of the PBKDF2 algorithm used in the RDB store. The value is an integer.
Default value: **10000**.
The value must be an integer greater than 0. If it is not an integer, the value is rounded down.
If this parameter is not specified or is set to **0**, the default value **10000** and the default encryption algorithm **AES_256_GCM** are used.| +| encryptionAlgo | [EncryptionAlgo](#encryptionalgo14) | No| Algorithm used for database encryption and decryption.
Default value: **AES_256_GCM**.| +| hmacAlgo | [HmacAlgo](#hmacalgo14) | No| HMAC algorithm used for database encryption and decryption.
Default value: **SHA256**.| +| kdfAlgo | [KdfAlgo](#kdfalgo14) | No| PBKDF2 algorithm used for database encryption and decryption.
Default value: the same as the HMAC algorithm used.| +| cryptoPageSize | number | No| Page size used for database encryption and decryption.
Default value: **1024** bytes.
The value must be an integer within the range of 1024 to 65536 and must be 2n. If the specified value is not an integer, the value is rounded down.| + +## HmacAlgo20+ + +Enumerates the HMAC algorithms for the database. Use the enum name rather than the enum value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Value | Description| +| ---- | ---- | ---- | +| SHA1 | 0 | HMAC_SHA1. | +| SHA256 | 1 | HMAC_SHA256. | +| SHA512 | 2 | HMAC_SHA512. | + +## KdfAlgo20+ + +Enumerates the PBKDF2 algorithms for the database. Use the enum name rather than the enum value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Value | Description| +| ---- | ---- | ---- | +| KDF_SHA1 | 0 | PBKDF2_HMAC_SHA1. | +| KDF_SHA256 | 1 | PBKDF2_HMAC_SHA256. | +| KDF_SHA512 | 2 | PBKDF2_HMAC_SHA512. | + +## Field20+ + +Enumerates the special fields used in predicates. Use the enum name rather than the enum value. + +**System capability**: SystemCapability.DistributedDataManager.CloudSync.Client + +| Name | Value | Description | +| -------------- | ---- | ---------------------------------- | +| CURSOR_FIELD | '#_cursor' | Field name to be searched based on the cursor.| +| ORIGIN_FIELD | '#_origin' | Data source to be searched based on the cursor. | +| DELETED_FLAG_FIELD | '#_deleted_flag' | Whether the dirty data (data deleted from the cloud) is cleared from the local device. It fills in the result set returned upon the cursor-based search.
The value **true** means the dirty data is cleared; the value **false** means the opposite.| +| DATA_STATUS_FIELD12+ | '#_data_status' | Data status in the cursor-based search result set. The value **0** indicates normal data status; **1** indicates that data is retained after the account is logged out; **2** indicates that data is deleted from the cloud; **3** indicates that data is deleted after the account is logged out.| +| OWNER_FIELD | '#_cloud_owner' | Party who shares the data. It fills in the result set returned when the owner of the shared data is searched.| +| PRIVILEGE_FIELD | '#_cloud_privilege' | Operation permission on the shared data. It fills in the result set returned when the permission on the shared data is searched.| +| SHARING_RESOURCE_FIELD | '#_sharing_resource_field' | Resource shared. It fills in the result set returned when the shared resource is searched.| + +## AssetStatus10+ + +Enumerates the asset statuses. Use the enum names instead of the enum values. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| ------------------------------- | --- | -------------- | +| ASSET_NORMAL | - | The asset is in normal status. | +| ASSET_INSERT | - | The asset is to be inserted to the cloud.| +| ASSET_UPDATE | - | The asset is to be updated to the cloud.| +| ASSET_DELETE | - | The asset is to be deleted from the cloud.| +| ASSET_ABNORMAL | - | The asset is in abnormal status. | +| ASSET_DOWNLOADING | - | The asset is being downloaded to a local device.| + +## Asset10+ + +Defines information about an asset (such as a document, image, and video). The asset APIs do not support **Datashare**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory | Description | +| ----------- | --------------------------- | --- | ------------ | +| name | string | Yes | Asset name. | +| uri | string | Yes | Asset URI, which is an absolute path in the system. | +| path | string | Yes | Application sandbox path of the asset. | +| createTime | string | Yes | Time when the asset was created. | +| modifyTime | string | Yes | Time when the asset was last modified.| +| size | string | Yes | Size of the asset. | +| status | [AssetStatus](#assetstatus10) | No | Asset status. The default value is **ASSET_NORMAL**. | + +## Assets10+ + +Defines an array of the [Asset](#asset10) type. + +| Type | Description | +| ------- | -------------------- | +| [Asset](#asset10)[] | Array of assets. | + +## ValueType + +Defines the data types allowed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Type | Description | +| ------- | -------------------- | +| null10+ | Null. | +| number | Number. | +| string | String. | +| boolean | Boolean.| +| Uint8Array10+ | Uint8 array. | +| Asset10+ | [Asset](#asset10). | +| Assets10+ | [Assets](#assets10).| + +## ValuesBucket + +Defines the types of the key and value in a KV pair. This type is not multi-thread safe. If a **ValuesBucket** instance is operated by multiple threads at the same time in an application, use a lock for the instance. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Key Type| Value Type | +| ------ | ----------------------- | +| string | [ValueType](#valuetype) | + +## SqlExecutionInfo20+ + +Represents statistics about SQL statements executed by the database. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Read-Only| Optional |Description | +| -------- | ------------------------------------------------- | ---- | ---- | -------------------------------------------------------- | +| sql12+ | Array<string> | Yes | No | SQL statements executed. If the value of [batchInsert](#batchinsert) is too large, there may be multiple SQL statements. | +| totalTime12+ | number | Yes | No | Total time used to execute the SQL statements, in μs. | +| waitTime12+ | number | Yes | No | Time used to obtain the handle, in μs. | +| prepareTime12+ | number | Yes | No | Time used to get the SQL statements ready and bind parameters, in μs. | +| executeTime12+ | number | Yes | No | Total time used to execute the SQL statements, in μs.| + +## TransactionType20+ + +Enumerates the types of transaction objects that can be created. Use the enum name rather than the enum value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| ---------------- | ---- | ------------------------ | +| DEFERRED | 0 | Deferred transaction object. When a deferred transaction object is created, automatic commit is disabled and no transaction will start. A read or write transaction starts only when the first read or write operation is performed. | +| IMMEDIATE | 1 | Immediate transaction object. When an immediate transaction object is created, a write transaction starts. If there is any uncommitted write transaction, the transaction object cannot be created and error 14800024 is returned.| +| EXCLUSIVE | 2 | Exclusive transaction object. In WAL mode, the exclusive transaction object is the same as the immediate transaction object. In other log modes, this type of transaction can prevent the database from being read by other connections during the transaction.| + +## TransactionOptions20+ + +Represents the configuration of a transaction object. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------- | ------------- | ---- | --------------------------------------------------------- | +| transactionType | [TransactionType](#transactiontype14) | No | Transaction object type.
Default value: **DEFERRED**. | + +## ConflictResolution10+ + +Defines the resolution to use when **insert()** and **update()** conflict. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| -------------------- | ---- | ------------------------------------------------------------ | +| ON_CONFLICT_NONE | 0 | No operation is performed.| +| ON_CONFLICT_ROLLBACK | 1 | Abort the SQL statement and roll back the current transaction. | +| ON_CONFLICT_ABORT | 2 | Abort the current SQL statement and revert any changes made by the current SQL statement. However, the changes made by the previous SQL statement in the same transaction are retained and the transaction remains active.| +| ON_CONFLICT_FAIL | 3 | Abort the current SQL statement. The **FAIL** resolution does not revert previous changes made by the failed SQL statement or end the transaction.| +| ON_CONFLICT_IGNORE | 4 | Skip the rows that contain constraint violations and continue to process the subsequent rows of the SQL statement.| +| ON_CONFLICT_REPLACE | 5 | Delete pre-existing rows that cause the constraint violation before inserting or updating the current row, and continue to execute the command normally.| + +## RdbPredicates + +Defines the predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. This type is not multi-thread safe. If an **RdbPredicates** instance is operated by multiple threads at the same time in an application, use a lock for the instance. + +### constructor + +constructor(name: string) + +A constructor used to create an **RdbPredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| name | string | Yes | Database table name.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +``` + +### equalTo + +equalTo(field: string, value: ValueType): RdbPredicates + + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "lisi"); +``` + + +### notEqualTo + +notEqualTo(field: string, value: ValueType): RdbPredicates + + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notEqualTo("NAME", "lisi"); +``` + + +### beginWrap + +beginWrap(): RdbPredicates + + +Adds a left parenthesis to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### endWrap + +endWrap(): RdbPredicates + +Adds a right parenthesis to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() +``` + +### or + +or(): RdbPredicates + +Adds the OR condition to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") +``` + +### and + +and(): RdbPredicates + +Adds the AND condition to the **RdbPredicates**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) +``` + +### contains + +contains(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string containing the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.contains("NAME", "os"); +``` + +### beginsWith + +beginsWith(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that starts with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.beginsWith("NAME", "os"); +``` + +### endsWith + +endsWith(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that ends with the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.endsWith("NAME", "se"); +``` + +### isNull + +isNull(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the field whose value is null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.isNull("NAME"); +``` + +### isNotNull + +isNotNull(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the field whose value is not null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.isNotNull("NAME"); +``` + +### like + +like(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match a string that is similar to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.like("NAME", "%os%"); +``` + +### glob + +glob(field: string, value: string): RdbPredicates + +Sets an **RdbPredicates** to match the specified string. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match the **RdbPredicates**.

Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.glob("NAME", "?h*g"); +``` + +### between + +between(field: string, low: ValueType, high: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | Yes | Column name in the database table. | +| low | [ValueType](#valuetype) | Yes | Minimum value to match the **RdbPredicates**. | +| high | [ValueType](#valuetype) | Yes | Maximum value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.between("AGE", 10, 50); +``` + +### notBetween + +notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | -------------------------- | +| field | string | Yes | Column name in the database table. | +| low | [ValueType](#valuetype) | Yes | Minimum value to match the **RdbPredicates**. | +| high | [ValueType](#valuetype) | Yes | Maximum value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notBetween("AGE", 10, 50); +``` + +### greaterThan + +greaterThan(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.greaterThan("AGE", 18); +``` + +### lessThan + +lessThan(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.lessThan("AGE", 20); +``` + +### greaterThanOrEqualTo + +greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.greaterThanOrEqualTo("AGE", 18); +``` + +### lessThanOrEqualTo + +lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | [ValueType](#valuetype) | Yes | Value to match the **RdbPredicates**.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.lessThanOrEqualTo("AGE", 20); +``` + +### orderByAsc + +orderByAsc(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the column with values sorted in ascending order. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.orderByAsc("NAME"); +``` + +### orderByDesc + +orderByDesc(field: string): RdbPredicates + +Sets an **RdbPredicates** to match the column with values sorted in descending order. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| field | string | Yes | Column name in the database table.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.orderByDesc("AGE"); +``` + +### distinct + +distinct(): RdbPredicates + +Sets an **RdbPredicates** to filter out duplicate records. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose").distinct(); +``` + +### limitAs + +limitAs(value: number): RdbPredicates + +Sets an **RdbPredicates** to specify the maximum number of records. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| value | number | Yes | Maximum number of records.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose").limitAs(3); +``` + +### offsetAs + +offsetAs(rowOffset: number): RdbPredicates + +Sets an **RdbPredicates** to specify the start position of the returned result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------------------------------- | +| rowOffset | number | Yes | Number of rows to offset from the beginning. The value is a positive integer.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose").offsetAs(3); +``` + +### groupBy + +groupBy(fields: Array<string>): RdbPredicates + +Sets an **RdbPredicates** to group rows that have the same value into summary rows. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | -------------------- | +| fields | Array<string> | Yes | Names of columns to group.| + +**Return value** + +| Type | Description | +| ------------------------------------ | ---------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.groupBy(["AGE", "NAME"]); +``` + +### indexedBy + +indexedBy(field: string): RdbPredicates + +Sets an **RdbPredicates** object to specify the index column. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| field | string | Yes | Name of the index column.| + +**Return value** + + +| Type | Description | +| ------------------------------------ | ------------------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.indexedBy("SALARY_INDEX"); +``` + +### in + +in(field: string, value: Array<ValueType>): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | --------------------------------------- | +| field | string | Yes | Column name in the database table. | +| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.in("AGE", [18, 20]); +``` + +### notIn + +notIn(field: string, value: Array<ValueType>): RdbPredicates + +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | ------------------------------------- | +| field | string | Yes | Column name in the database table. | +| value | Array<[ValueType](#valuetype)> | Yes | Array of **ValueType**s to match.| + +**Return value** + +| Type | Description | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Example** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notIn("NAME", ["Lisa", "Rose"]); +``` + +### notContains20+ + +notContains(field: string, value: string): RdbPredicates + +Creates an **RdbPredicates** object to search for the records that do not contain the given value in the specified column. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match.| + +**Return value** + +| Type | Description | +| ------------------------------- | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| **ID**| **Error Message** | +| --------- |----------------------------------------------------------------------------------------------------------------| +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | + +**Example** + +```ts +// Find the records that do not contain the string "os" in the NAME column, for example, Lisa. +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notContains("NAME", "os"); +``` + +### notLike20+ + +notLike(field: string, value: string): RdbPredicates + +Creates an **RdbPredicates** object to search for the records that are not similar to the given value in the specified column. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| field | string | Yes | Column name in the database table. | +| value | string | Yes | Value to match.| + +**Return value** + +| Type | Description | +| ------------------------------- | -------------------------- | +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| **ID**| **Error Message** | +| --------- |----------------------------------------------------------------------------------------------------------------| +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | + +**Example** + +```ts +// Find the records that are not "os" in the NAME column, for example, Rose. +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notLike("NAME", "os"); +``` + +## RdbStore + +Provides APIs to manage an RDB store. + +Before using the APIs of this class, use [executeSql](#executesql) to initialize the database table structure and related data. + +### Attributes10+ + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------ | ----------- | ---- | -------------------------------- | +| version10+ | number | Yes | RDB store version, which is an integer greater than 0. | + +**Example** + +```ts +// Set the RDB store version. +if(store != undefined) { + (store as relationalStore.RdbStore).version = 3; + // Obtain the RDB store version. + console.info(`RdbStore version is ${store.version}`); +} +``` + +### insert + +insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void + +Inserts a row of data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ---------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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 + +Inserts a row of data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ---------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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> + +Inserts a row of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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> + +Inserts a row of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert.| +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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}`); + }) +} +``` + +### insertSync20+ + +insertSync(table: string, values: sendableRelationalStore.ValuesBucket, conflict?: ConflictResolution):number + +Inserts a row of Sendable data into a table. This API returns the result synchronously. Due to the limit of the shared memory (max. 2 MB), a single data record cannot exceed 2 MB. Otherwise, the query operation will fail. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------------------------- | +| table | string | Yes | Name of the target table. | +| values | [sendableRelationalStore.ValuesBucket](./js-apis-data-sendableRelationalStore.md#valuesbucket) | Yes | Sendable data to insert. | +| conflict | [ConflictResolution](#conflictresolution10) | 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](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 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. | +| 14800015 | The database does not respond. | +| 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. | +| 14800047 | The WAL file size exceeds the default limit. | + +**Example** + +```ts +import { sendableRelationalStore } from '@kit.ArkData'; + +const valuesBucket: relationalStore.ValuesBucket = { + "NAME": 'hangman', + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3]) +}; +const sendableValuesBucket = sendableRelationalStore.toSendableValuesBucket(valuesBucket); + +if (store != undefined) { + try { + let rowId: number = (store as relationalStore.RdbStore).insertSync("EMPLOYEE", sendableValuesBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); + console.info(`Insert is successful, rowId = ${rowId}`); + } catch (error) { + console.error(`Insert is failed, code is ${error.code},message is ${error.message}`); + } +} +``` + +### batchInsert + +batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void + +Batch inserts data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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> + +Batch inserts data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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> + +Creates a transaction object and starts a transaction. This API uses a promise to return the result. + +Different from [beginTransaction](#begintransaction), **createTransaction()** returns a transaction object, which is isolated from other transaction objects. When a transaction object is used to insert, delete, or update data, these changes cannot be detected by [on ('dataChange')](#ondatachange). + +A store supports a maximum of four transaction objects at a time. If the number of transaction objects exceeds the upper limit, error 14800015 is returned. In this case, check whether transaction objects are being held too long or whether there are too many concurrent transactions. If the problem cannot be solved through these optimizations, you are advised to create transaction objects after existing transactions are released. + +You are advised to use **createTransaction** instead of **beginTransaction**. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ----------------------------- | ---- | ------------------------------------------------------------ | +| options | [TransactionOptions](#transactionoptions14) | No | Configuration of the transaction object to create. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<[Transaction](#transaction14)> | Promise used to return the transaction object created.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +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 + +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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 + +Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows updated. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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> + +Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------ | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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> + +Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| conflict | [ConflictResolution](#conflictresolution10) | Yes | Resolution used to resolve the conflict. | + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------- | +| Promise<number> | Promise used to return the number of rows updated.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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 + +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data.| +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of rows deleted. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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> + +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise<number> | Promise used to return the number of rows deleted.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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 + +Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**Example** + +```ts +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 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 dataset memory. + resultSet.close(); + }) +} +``` + +### query + +query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void + +Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | Yes | Columns to query. If this parameter is not specified, the query applies to all columns. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**Example** + +```ts +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 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 dataset memory. + resultSet.close(); + }) +} +``` + +### query + +query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> + +Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```ts +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 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 dataset memory. + 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 + +Queries data using the specified SQL statement. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**Example** + +```ts +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 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 dataset memory. + resultSet.close(); + }) +} +``` + +### querySql + +querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void + +Queries data using the specified SQL statement. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array.| +| callback | AsyncCallback<[ResultSet](#resultset)> | Yes | Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**Example** + +```ts +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 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 dataset memory. + resultSet.close(); + }) +} +``` + +### querySql + +querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> + +Queries data using the specified SQL statement. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. 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](#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 [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**Example** + +```ts +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 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 dataset memory. + 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 + +Executes an SQL statement that contains specified arguments but returns no value. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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 + +Executes an SQL statement that contains specified arguments but returns no value. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | Yes | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, the value of this parameter must be an empty array.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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> + +Executes an SQL statement that contains specified arguments but returns no value. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| bindArgs | Array<[ValueType](#valuetype)> | No | Arguments in the SQL statement. The value corresponds to the placeholders in the SQL parameter statement. If the SQL parameter statement is complete, leave this parameter blank.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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 + +Starts the transaction before executing an SQL statement. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**Example** + +```ts +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 + +Commits the executed SQL statements. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```ts +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 + +Rolls back the SQL statements that have been executed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```ts +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 + +Backs up an RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| destName | string | Yes | Name of the RDB store backup file.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**Example** + +```ts +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> + +Backs up an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------ | +| destName | string | Yes | Name of the RDB store backup file.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**Example** + +```ts +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 + +Restores an RDB store from a backup file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| srcName | string | Yes | Name of the RDB store backup file.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**Example** + +```ts +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> + +Restores an RDB store from a backup file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------ | +| srcName | string | Yes | Name of the RDB store backup file.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**Example** + +```ts +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 + +Subscribes to SQL statistics. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ |---------------------------------| ---- |-----------------------------------| +| event | string | Yes | Event type. The value is **'statistics'**, which indicates the statistics of the SQL execution time.| +| observer | Callback<[SqlExecutionInfo](#sqlexecutioninfo12)> | Yes | Callback used to return the statistics about the SQL execution time in the database. | + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). + +| **ID**| **Error Message** | +|-----------|--------| +| 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. | + +**Example** + +```ts +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> + +Closes this RDB store. This API uses a promise to return the result. + +**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](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ----------------------------------------------- | +| 401 | Parameter error. The store must not be nullptr. | +| 14800000 | Inner error. | + +**Example** + +```ts +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 + +Provides APIs to access the result set obtained by querying the RDB store. A result set is a set of results returned after **query()** is called. + +### Usage + +Obtain the **resultSet** object first. + +```ts +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}`); + }); +} +``` + +### Attributes + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Type | Mandatory| Description | +| ------------ | ------------------- | ---- | -------------------------------- | +| columnNames | Array<string> | Yes | Names of all columns in the result set. | +| columnCount | number | Yes | Number of columns in the result set. | +| rowCount | number | Yes | Number of rows in the result set. | +| rowIndex | number | Yes | Index of the current row in the result set. | +| isAtFirstRow | boolean | Yes | Whether the cursor is in the first row of the result set. | +| isAtLastRow | boolean | Yes | Whether the cursor is in the last row of the result set. | +| isEnded | boolean | Yes | Whether the cursor is after the last row of the result set.| +| isStarted | boolean | Yes | Whether the cursor has been moved. | +| isClosed | boolean | Yes | Whether the result set is closed. | + +### getColumnIndex + +getColumnIndex(columnName: string): number + +Obtains the column index based on the column name. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | -------------------------- | +| columnName | string | Yes | Column name.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Column index obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + +```ts +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 + +Obtains the column name based on the specified column index. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | -------------------------- | +| columnIndex | number | Yes | Column index.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Column name obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + +```ts +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 + +Moves the cursor to the row based on the specified offset. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| offset | number | Yes | Offset relative to the current position.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goTo(1); +} +``` + +### goToRow + +goToRow(position: number): boolean + +Moves to the specified row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------ | +| position | number | Yes | Destination position to move to.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goToRow(5); +} +``` + +### goToFirstRow + +goToFirstRow(): boolean + + +Moves to the first row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goToFirstRow(); +} +``` + +### goToLastRow + +goToLastRow(): boolean + +Moves to the last row of the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goToLastRow(); +} +``` + +### goToNextRow + +goToNextRow(): boolean + +Moves to the next row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goToNextRow(); +} +``` + +### goToPreviousRow + +goToPreviousRow(): boolean + +Moves to the previous row in the result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**Example** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goToPreviousRow(); +} +``` + +### getBlob + +getBlob(columnIndex: number): Uint8Array + +Obtains the value in the form of a byte array based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ---------- | -------------------------------- | +| Uint8Array | Value obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + +```ts +if(resultSet != undefined) { +const codes = (resultSet as relationalStore.ResultSet).getBlob((resultSet as relationalStore.ResultSet).getColumnIndex("CODES")); +} +``` + +### getValue20+ + +getValue(columnIndex: number): ValueType + +Obtains the value from the specified column and current row. If the value type is any of **ValueType**, the value of the corresponding type will be returned. Otherwise, **14800000** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ---------- | -------------------------------- | +| [ValueType](#valuetype) | Values of the specified type.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------|---------| +| 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. | + +**Example** + +```ts +if (resultSet != undefined) { + const codes = (resultSet as relationalStore.ResultSet).getValue((resultSet as relationalStore.ResultSet).getColumnIndex("BIGINT_COLUMN")); +} +``` + +### getString + +getString(columnIndex: number): string + +Obtains the value in the form of a string based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| string | String obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + +```ts +if(resultSet != undefined) { +const name = (resultSet as relationalStore.ResultSet).getString((resultSet as relationalStore.ResultSet).getColumnIndex("NAME")); +} +``` + +### getLong + +getLong(columnIndex: number): number + +Obtains the value of the Long type based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | ------------------------------------------------------------ | +| number | Value obtained.
The value range supported by API is **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. If the value is out of this range, use [getDouble](#getdouble).| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + +```ts +if(resultSet != undefined) { +const age = (resultSet as relationalStore.ResultSet).getLong((resultSet as relationalStore.ResultSet).getColumnIndex("AGE")); +} +``` + +### getDouble + +getDouble(columnIndex: number): number + +Obtains the value of the double type based on the specified column and the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------- | +| number | Returns the value obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + +```ts +if(resultSet != undefined) { +const salary = (resultSet as relationalStore.ResultSet).getDouble((resultSet as relationalStore.ResultSet).getColumnIndex("SALARY")); +} +``` + +### getAsset10+ + +getAsset(columnIndex: number): Asset + +Obtains the value in the [Asset](#asset10) format based on the specified column and current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | --- | ------------ | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| --------------- | -------------------------- | +| [Asset](#asset10) | Returns the value obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| --------- | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + +```ts +if(resultSet != undefined) { +const doc = (resultSet as relationalStore.ResultSet).getAsset((resultSet as relationalStore.ResultSet).getColumnIndex("DOC")); +} +``` + +### getAssets10+ + +getAssets(columnIndex: number): Assets + +Obtains the value in the [Assets](#assets10) format based on the specified column and current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------ | --- | ------------ | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ---------------- | ---------------------------- | +| [Assets](#assets10)| Returns the value obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + +```ts +if(resultSet != undefined) { +const docs = (resultSet as relationalStore.ResultSet).getAssets((resultSet as relationalStore.ResultSet).getColumnIndex("DOCS")); +} +``` + +### getRow20+ + +getRow(): ValuesBucket + +Obtains the data in the current row. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Return value** + +| Type | Description | +| ---------------- | ---------------------------- | +| [ValuesBucket](#valuesbucket) | Data obtained.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +if (resultSet != undefined) { + const row = (resultSet as relationalStore.ResultSet).getRow(); +} +``` + +### isColumnNull + +isColumnNull(columnIndex: number): boolean + +Checks whether the value in the specified column is null. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | Yes | Index of the target column, starting from 0.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------------------------- | +| boolean | Returns **true** if the value is null; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**Example** + +```ts +if(resultSet != undefined) { +const isColumnNull = (resultSet as relationalStore.ResultSet).isColumnNull((resultSet as relationalStore.ResultSet).getColumnIndex("CODES")); +} +``` + +### close + +close(): void + +Closes this result set. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).close(); +} +``` + +**Error codes** + +For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +## Transaction20+ + +Provides API for managing databases in transaction mode. A transaction object is created by using [createTransaction](#createtransaction14). Operations on different transaction objects are isolated. For details about the transaction types, see [TransactionType](#transactiontype14). + +Currently, an RDB store supports only one write transaction at a time. If the current [RdbStore](#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](#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. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Example** + +```ts +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`); + // 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}`); + }); + } + } +} +``` + +### commit20+ + +commit(): Promise<void> + +Commits the executed SQL statements. 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](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +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> + +Rolls back the executed SQL statement. 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](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +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> + +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 (max. 2 MB), a single data record cannot exceed 2 MB. Otherwise, the query operation will fail. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------------------- | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) | Yes | Row of data to insert.| +| conflict | [ConflictResolution](#conflictresolution10) | 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](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); + +// You can use either of the following: +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}`); + }); +} +``` + +### insertSync20+ + +insertSync(table: string, values: ValuesBucket | sendableRelationalStore.ValuesBucket, conflict?: ConflictResolution): number + +Inserts a row of data into a table. Due to the limit of the shared memory (max. 2 MB), a single data record cannot exceed 2 MB. Otherwise, the query operation will fail. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| table | string | Yes | Name of the target table. | +| values | [ValuesBucket](#valuesbucket) \| [sendableRelationalStore.ValuesBucket](./js-apis-data-sendableRelationalStore.md#valuesbucket) | Yes | Row of data to insert. | +| conflict | [ConflictResolution](#conflictresolution10) | 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](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +let value1 = "Lisa"; +let value2 = 18; +let value3 = 100.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); + +// You can use either of the following: +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) => { + try { + let rowId: number = (transaction as relationalStore.Transaction).insertSync("EMPLOYEE", valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); + transaction.commit(); + console.info(`Insert is successful, rowId = ${rowId}`); + } catch (e) { + 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> + +Inserts a batch of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +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 + +Inserts a batch of data into a table. This API returns the result synchronously. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------------------------- | +| 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](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +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> + +Inserts a batch of data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| +| conflict | [ConflictResolution](#conflictresolution10) | 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](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +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 + +Inserts a batch of data into a table. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------ | ---- | ---------------------------- | +| table | string | Yes | Name of the target table. | +| values | Array<[ValuesBucket](#valuesbucket)> | Yes | An array of data to insert.| +| conflict | [ConflictResolution](#conflictresolution10) | 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](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +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> + +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 (max. 2 MB), a single data record cannot exceed 2 MB. Otherwise, the query operation will fail. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| conflict | [ConflictResolution](#conflictresolution10) | 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](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); + +// You can use either of the following: +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 + +Updates data in the database based on the specified **RdbPredicates** instance. Due to the limit of the shared memory (max. 2 MB), a single data record cannot exceed 2 MB. Otherwise, the query operation will fail. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| values | [ValuesBucket](#valuesbucket) | Yes | Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Update conditions specified by the **RdbPredicates** object. | +| conflict | [ConflictResolution](#conflictresolution10) | No | Resolution used to resolve the conflict.
Default value: **relationalStore.ConflictResolution.ON_CONFLICT_NONE**.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | return the number of rows updated.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +let value1 = "Rose"; +let value2 = 22; +let value3 = 200.5; +let value4 = new Uint8Array([1, 2, 3, 4, 5]); + +// You can use either of the following: +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> + +Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ----------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise<number> | Promise used to return the number of rows deleted.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +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 + +Deletes data from the database based on the specified **RdbPredicates** object. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------- | ---- | --------------------------------------- | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Conditions specified by the **RdbPredicates** object for deleting data.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | return the number of rows deleted.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +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> + +Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. Due to the limit of the shared memory (max. 2 MB), a single data record cannot exceed 2 MB. Otherwise, the query operation will fail. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------ | ---- | ------------------------------------------------ | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```ts +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 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(); + 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 + +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](../apis-arkts/js-apis-taskpool.md) thread. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| predicates | [RdbPredicates](#rdbpredicates) | Yes | Query conditions specified by the **RdbPredicates** object. | +| columns | Array<string> | No | Columns to query. If this parameter is not specified, the query applies to all columns.
Default value: null.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 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. | + +**Return value** + +| Type | Description | +| ----------------------- | ----------------------------------- | +| [ResultSet](#resultset) | If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```ts +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 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(); + 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> + +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 1000. 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](#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](#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](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +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 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(); + 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 + +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 1000. 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](../apis-arkts/js-apis-taskpool.md) thread. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| args | Array<[ValueType](#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.
Default value: null.| + +**Return value** + +| Type | Description | +| ----------------------- | ----------------------------------- | +| [ResultSet](#resultset) | If the operation is successful, a **ResultSet** object will be returned.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +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 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(); + 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> + +Executes an SQL statement that contains specified arguments. The number of relational operators between expressions and operators in the statement cannot exceed 1000. 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](#querysql14) or [query](#query14) to query data, and use [attach](#attach12) to attach a database. + +Statements separated by semicolons (\;) are not supported. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| args | Array<[ValueType](#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](#valuetype)> | Promise used to return the SQL execution result.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +|-----------| ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +// Delete all data from the table. +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 + +Executes an SQL statement that contains specified arguments. The number of relational operators between expressions and operators in the statement cannot exceed 1000. This API returns a value of theValueType 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](#querysql14) or [query](#query14) to query data, and use [attach](#attach12) to attach a database. + +Statements separated by semicolons (\;) are not supported. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | Yes | SQL statement to run. | +| args | Array<[ValueType](#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.
Default value: null.| + +**Return value** + +| Type | Description | +| ----------------------- | ------------------- | +| [ValueType](#valuetype) | SQL execution result.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [RDB Store Error Codes](errorcode-data-rdb.md). For details about how to handle error 14800011, see [Database Backup and Restore](../../database/data-backup-and-restore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------------------------------------------------ | +| 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. | + +**Example** + +```ts +// Delete all data from the table. +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}`); + }); +} +``` diff --git a/arkuix/js-apis-request.md b/arkuix/js-apis-request.md new file mode 100644 index 0000000000000000000000000000000000000000..97d4616967b5f22078478296f38a10de9c732830 --- /dev/null +++ b/arkuix/js-apis-request.md @@ -0,0 +1,3483 @@ +# @ohos.request (Upload and Download) + +The **request** module provides applications with basic upload, download, and background transmission agent capabilities. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +```js +import request from '@ohos.request'; +``` + +## Constants + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +### Network Types +You can set **networkType** in [DownloadConfig](#downloadconfig) to specify the network type for the download service. + +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| NETWORK_MOBILE | number | 0x00000001 | Whether download is allowed on a mobile network.| +| NETWORK_WIFI | number | 0x00010000 | Whether download is allowed on a WLAN.| + +### Download Error Codes +The table below lists the values of **err** in the callback of [on('fail')7+](#onfail7) and the values of **failedReason** returned by [getTaskInfo9+](#gettaskinfo9). + +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| ERROR_CANNOT_RESUME7+ | number | 0 | Failure to resume the download due to network errors.| +| ERROR_DEVICE_NOT_FOUND7+ | number | 1 | Failure to find a storage device such as a memory card.| +| ERROR_FILE_ALREADY_EXISTS7+ | number | 2 | Failure to download the file because it already exists.| +| ERROR_FILE_ERROR7+ | number | 3 | File operation failure.| +| ERROR_HTTP_DATA_ERROR7+ | number | 4 | HTTP transmission failure.| +| ERROR_INSUFFICIENT_SPACE7+ | number | 5 | Insufficient storage space.| +| ERROR_TOO_MANY_REDIRECTS7+ | number | 6 | Error caused by too many network redirections.| +| ERROR_UNHANDLED_HTTP_CODE7+ | number | 7 | Unidentified HTTP code.| +| ERROR_UNKNOWN7+ | number | 8 | Unknown error.| +| ERROR_OFFLINE9+ | number | 9 | No network connection.| +| ERROR_UNSUPPORTED_NETWORK_TYPE9+ | number | 10 | Network type mismatch.| + + +### Causes of Download Pause +The table below lists the values of **pausedReason** returned by [getTaskInfo9+](#gettaskinfo9). + +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| PAUSED_QUEUED_FOR_WIFI7+ | number | 0 | Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a mobile network session.| +| PAUSED_WAITING_FOR_NETWORK7+ | number | 1 | Download paused due to a network connection problem, for example, network disconnection.| +| PAUSED_WAITING_TO_RETRY7+ | number | 2 | Download paused and then retried.| +| PAUSED_BY_USER9+ | number | 3 | The user paused the session.| +| PAUSED_UNKNOWN7+ | number | 4 | Download paused due to unknown reasons.| + +### Download Task Status Codes +The table below lists the values of **status** returned by [getTaskInfo9+](#gettaskinfo9). + +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| SESSION_SUCCESSFUL7+ | number | 0 | Successful download.| +| SESSION_RUNNING7+ | number | 1 | Download in progress.| +| SESSION_PENDING7+ | number | 2 | Download pending.| +| SESSION_PAUSED7+ | number | 3 | Download paused.| +| SESSION_FAILED7+ | number | 4 | Download failure without retry.| + + +## request.uploadFile9+ + +uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> + +Uploads files. This API uses a promise to return the result. You can use [on('complete'|'fail')9+](#oncomplete--fail9) to obtain the upload error information. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400002 | bad file path. | + +**Example** + + ```js + let uploadTask; + let uploadConfig = { + url: 'http://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], + }; + try { + request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => { + uploadTask = data; + }).catch((err) => { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } + ``` + + +## request.uploadFile9+ + +uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void + +Uploads files. This API uses an asynchronous callback to return the result. You can use [on('complete'|'fail')9+](#oncomplete--fail9) to obtain the upload error information. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400002 | bad file path. | + +**Example** + + ```js + let uploadTask; + let uploadConfig = { + url: 'http://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], + }; + try { + request.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => { + if (err) { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + return; + } + uploadTask = data; + }); + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } + ``` + +## UploadTask + +Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object through [request.uploadFile9+](#requestuploadfile9) in promise mode or [request.uploadFile9+](#requestuploadfile9-1) in callback mode. + + + +### on('progress') + +on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => void): void + +Subscribes to upload progress events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| +| callback | function | Yes| Callback for the upload progress event.| + + Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| uploadedSize | number | Yes| Size of the uploaded files, in bytes.| +| totalSize | number | Yes| Total size of the files to upload, in bytes.| + +**Example** + + ```js + let upProgressCallback = (uploadedSize, totalSize) => { + console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); + }; + uploadTask.on('progress', upProgressCallback); + ``` + + +### on('headerReceive')7+ + +on(type: 'headerReceive', callback: (header: object) => void): void + +Subscribes to HTTP header events for an upload task. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).| +| callback | function | Yes| Callback for the HTTP Response Header event.| + + Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| header | object | Yes| HTTP Response Header.| + +**Example** + + ```js + let headerCallback = (headers) => { + console.info("upOnHeader headers:" + JSON.stringify(headers)); + }; + uploadTask.on('headerReceive', headerCallback); + ``` + + +### on('complete' | 'fail')9+ + + on(type:'complete' | 'fail', callback: Callback<Array<TaskState>>): void; + +Subscribes to upload completion or failure events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| +| callback | Callback<Array<TaskState>> | Yes| Callback used to return the result.| + + Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| taskstates | Array<[TaskState](#taskstate9)> | Yes| Upload result.| + +**Example** + + ```js + let upCompleteCallback = (taskStates) => { + for (let i = 0; i < taskStates.length; i++ ) { + console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); + } + }; + uploadTask.on('complete', upCompleteCallback); + + let upFailCallback = (taskStates) => { + for (let i = 0; i < taskStates.length; i++ ) { + console.info("upOnFail taskState:" + JSON.stringify(taskStates[i])); + } + }; + uploadTask.on('fail', upFailCallback); + ``` + + +### off('progress') + +off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) => void): void + +Unsubscribes from upload progress events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| +| callback | function | No| Callback used to return the result.
**uploadedSize**: size of the uploaded files, in bytes.
**totalSize**: Total size of the files to upload, in bytes. | + +**Example** + + ```js + let upProgressCallback = (uploadedSize, totalSize) => { + console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize); + }; + uploadTask.off('progress', upProgressCallback); + ``` + + +### off('headerReceive')7+ + +off(type: 'headerReceive', callback?: (header: object) => void): void + +Unsubscribes from HTTP header events for an upload task. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).| +| callback | function | No| Callback used to return the result.
**header**: HTTP response header.| + +**Example** + + ```js + let headerCallback = (header) => { + console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`); + }; + uploadTask.off('headerReceive', headerCallback); + ``` + +### off('complete' | 'fail')9+ + + off(type:'complete' | 'fail', callback?: Callback<Array<TaskState>>): void; + +Unsubscribes from upload completion or failure events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| +| callback | Callback<Array<TaskState>> | No| Callback used to return the result.
**taskstates**: upload task result.| + +**Example** + + ```js + let upCompleteCallback = (taskStates) => { + console.info('Upload delete complete notification.'); + for (let i = 0; i < taskStates.length; i++ ) { + console.info('taskState:' + JSON.stringify(taskStates[i])); + } + }; + uploadTask.off('complete', upCompleteCallback); + + let upFailCallback = (taskStates) => { + console.info('Upload delete fail notification.'); + for (let i = 0; i < taskStates.length; i++ ) { + console.info('taskState:' + JSON.stringify(taskStates[i])); + } + }; + uploadTask.off('fail', upFailCallback); + ``` + +### delete9+ +delete(): Promise<boolean> + +Deletes this upload task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.| + +**Example** + + ```js + uploadTask.delete().then((result) => { + if (result) { + console.info('Upload task removed successfully. '); + } else { + console.error('Failed to remove the upload task. '); + } + }).catch((err) => { + console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); + }); + ``` + + +### delete9+ + +delete(callback: AsyncCallback<boolean>): void + +Deletes this upload task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| + +**Example** + + ```js + uploadTask.delete((err, result) => { + if (err) { + console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Upload task removed successfully.'); + } else { + console.error('Failed to remove the upload task.'); + } + }); + ``` + + +## UploadConfig +Describes the configuration for an upload task. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| Resource URL.| +| header | Object | Yes| HTTP or HTTPS header added to an upload request.| +| method | string | Yes| Request method, which can be **'POST'** or **'PUT'**. The default value is **'POST'**.| +| files | Array<[File](#file)> | Yes| List of files to upload, which is submitted through **multipart/form-data**.| +| data | Array<[RequestData](#requestdata)> | Yes| Form data in the request body.| +| index20+ | number | No| Path index of the task. The default value is **0**.| +| begins20+ | number | No| Start point of the file read when the upload task begins. The default value is **0**. The value is a closed interval, indicating that the file is read from the beginning.| +| ends20+ | number | No| End point of the file read when the upload task is complete. The default value is **-1**. The value is a closed interval, indicating that the file is read till the end.| + +## TaskState9+ +Implements a **TaskState** object, which is the callback parameter of the [on('complete' | 'fail')9+](#oncomplete--fail9) and [off('complete' | 'fail')9+](#offcomplete--fail9) APIs. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| path | string | Yes| File path.| +| responseCode | number | Yes| Return value of an upload task.| +| message | string | Yes| Description of the upload task result.| + +## File +Describes the list of files in [UploadConfig](#uploadconfig). + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| filename | string | Yes| File name in the header when **multipart** is used.| +| name | string | Yes| Name of a form item when **multipart** is used. The default value is **file**.| +| uri | string | Yes| Local path for storing files.
Only the **internal** protocol type is supported. In the value, **internal://cache/** is mandatory. Example:
internal://cache/path/to/file.txt | +| type | string | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| + + +## RequestData +Describes the form data in [UploadConfig](#uploadconfig). + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of a form element.| +| value | string | Yes| Value of a form element.| + +## request.downloadFile9+ + +downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> + +Downloads files. This API uses a promise to return the result. You can use [on('complete'|'pause'|'remove')7+](#oncompletepauseremove7) to obtain the download task state, which can be completed, paused, or removed. You can also use [on('fail')7+](#onfail7) to obtain the task download error information. + + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | file operation error. | +| 13400002 | bad file path. | +| 13400003 | task manager service error. | + +**Example** + + ```js + let downloadTask; + try { + request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + downloadTask = data; + }).catch((err) => { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + }) + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } + ``` + + +## request.downloadFile9+ + +downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; + +Downloads files. This API uses an asynchronous callback to return the result. You can use [on('complete'|'pause'|'remove')7+](#oncompletepauseremove7) to obtain the download task state, which can be completed, paused, or removed. You can also use [on('fail')7+](#onfail7) to obtain the task download error information. + + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | file operation error. | +| 13400002 | bad file path. | +| 13400003 | task manager service error. | + +**Example** + + ```js + let downloadTask; + try { + request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + filePath: 'xxx/xxxxx.hap'}, (err, data) => { + if (err) { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + return; + } + downloadTask = data; + }); + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } + ``` + +## DownloadTask + +Implements file downloads. Before using any APIs of this class, you must obtain a **DownloadTask** object through [request.downloadFile9+](#requestdownloadfile9) in promise mode or [request.downloadFile9+](#requestdownloadfile9-1) in callback mode. + + +### on('progress') + +on(type: 'progress', callback:(receivedSize: number, totalSize: number) => void): void + +Subscribes to download progress events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| +| callback | function | Yes| Callback used to return the result.| + + Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| receivedSize | number | Yes| Size of the downloaded files, in bytes.| +| totalSize | number | Yes| Total size of the files to download, in bytes.| + +**Example** + + ```js + let progresCallback = (receivedSize, totalSize) => { + console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); + }; + downloadTask.on('progress', progresCallback); + ``` + + +### off('progress') + +off(type: 'progress', callback?: (receivedSize: number, totalSize: number) => void): void + +Unsubscribes from download progress events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| +| callback | function | No| Callback used to return the result.
**receivedSize**: size of the downloaded files.
**totalSize**: total size of the files to download.| + +**Example** + + ```js + let progresCallback = (receivedSize, totalSize) => { + console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); + }; + downloadTask.off('progress', progresCallback); + ``` + + +### on('complete'|'pause'|'remove')7+ + +on(type: 'complete'|'pause'|'remove', callback:() => void): void + +Subscribes to download events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | Yes| Callback used to return the result.| + +**Example** + + ```js + let completeCallback = () => { + console.info('Download task completed.'); + }; + downloadTask.on('complete', completeCallback); + + let pauseCallback = () => { + console.info('Download task pause.'); + }; + downloadTask.on('pause', pauseCallback); + + let removeCallback = () => { + console.info('Download task remove.'); + }; + downloadTask.on('remove', removeCallback); + ``` + + +### off('complete'|'pause'|'remove')7+ + +off(type: 'complete'|'pause'|'remove', callback?:() => void): void + +Unsubscribes from download events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | No| Callback used to return the result.| + +**Example** + + ```js + let completeCallback = () => { + console.info('Download delete complete notification.'); + }; + downloadTask.off('complete', completeCallback); + + let pauseCallback = () => { + console.info('Download delete pause notification.'); + }; + downloadTask.off('pause', pauseCallback); + + let removeCallback = () => { + console.info('Download delete remove notification.'); + }; + downloadTask.off('remove', removeCallback); + ``` + + +### on('fail')7+ + +on(type: 'fail', callback: (err: number) => void): void + +Subscribes to download failure events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| +| callback | function | Yes| Callback for the download task failure event.| + + Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| err | number | Yes| Error code of the download failure. For details about the error codes, see [Download Error Codes](#download-error-codes).| + +**Example** + + ```js + let failCallback = (err) => { + console.info('Download task failed. Cause:' + err); + }; + downloadTask.on('fail', failCallback); + ``` + + +### off('fail')7+ + +off(type: 'fail', callback?: (err: number) => void): void + +Unsubscribes from download failure events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| +| callback | function | No| Callback used to return the result.
**err**: error code of the download failure. | + +**Example** + + ```js + let failCallback = (err) => { + console.info(`Download delete fail notification. err: ${err.message}`); + }; + downloadTask.off('fail', failCallback); + ``` + +### delete9+ + +delete(): Promise<boolean> + +Removes this download task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result.| + +**Example** + + ```js + downloadTask.delete().then((result) => { + if (result) { + console.info('Download task removed.'); + } else { + console.error('Failed to remove the download task.'); + } + }).catch ((err) => { + console.error('Failed to remove the download task.'); + }); + ``` + + +### delete9+ + +delete(callback: AsyncCallback<boolean>): void + +Deletes this download task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task deletion result.| + +**Example** + + ```js + downloadTask.delete((err, result)=>{ + if(err) { + console.error('Failed to remove the download task.'); + return; + } + if (result) { + console.info('Download task removed.'); + } else { + console.error('Failed to remove the download task.'); + } + }); + ``` + + +### getTaskInfo9+ + +getTaskInfo(): Promise<DownloadInfo> + +Obtains the information about this download task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information.| + +**Example** + + ```js + downloadTask.getTaskInfo().then((downloadInfo) => { + console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) + }) .catch((err) => { + console.error('Failed to query the download task. Cause:' + err) + }); + ``` + + +### getTaskInfo9+ + +getTaskInfo(callback: AsyncCallback<DownloadInfo>): void + +Obtains the information about this download task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| + +**Example** + + ```js + downloadTask.getTaskInfo((err, downloadInfo)=>{ + if(err) { + console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); + } else { + console.info('download query success. data:'+ JSON.stringify(downloadInfo)); + } + }); + ``` + + +### getTaskMimeType9+ + +getTaskMimeType(): Promise<string> + +Obtains the **MimeType** of this download task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the **MimeType** of the download task.| + +**Example** + + ```js + downloadTask.getTaskMimeType().then((data) => { + console.info('Download task queried. Data:' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) + }); + ``` + + +### getTaskMimeType9+ + +getTaskMimeType(callback: AsyncCallback<string>): void; + +Obtains the **MimeType** of this download task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| + +**Example** + + ```js + downloadTask.getTaskMimeType((err, data)=>{ + if(err) { + console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); + } else { + console.info('Download task queried. data:' + JSON.stringify(data)); + } + }); + ``` + + +### suspend9+ + +suspend(): Promise<boolean> + +Pauses this download task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the download task pause result.| + +**Example** + + ```js + downloadTask.suspend().then((result) => { + if (result) { + console.info('Download task paused. '); + } else { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); + } + }).catch((err) => { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); + }); + ``` + + +### suspend9+ + +suspend(callback: AsyncCallback<boolean>): void + +Pauses this download task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| + +**Example** + + ```js + downloadTask.suspend((err, result)=>{ + if(err) { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Download task paused. '); + } else { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); + } + }); + ``` + + +### restore9+ + +restore(): Promise<boolean> + +Resumes this download task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + + ```js + downloadTask.restore().then((result) => { + if (result) { + console.info('Download task resumed.') + } else { + console.error('Failed to resume the download task. '); + } + console.info('Download task resumed.') + }).catch((err) => { + console.error('Failed to resume the download task. Cause:' + err); + }); + ``` + + +### restore9+ + +restore(callback: AsyncCallback<boolean>): void + +Resumes this download task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| + +**Example** + + ```js + downloadTask.restore((err, result)=>{ + if (err) { + console.error('Failed to resume the download task. Cause:' + err); + return; + } + if (result) { + console.info('Download task resumed.'); + } else { + console.error('Failed to resume the download task.'); + } + }); + ``` + +## DownloadConfig +Defines the download task configuration. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| Resource URL.| +| header | Object | No| HTTPS flag header to be included in the download request.
The **X-TLS-Version** parameter in **header** specifies the TLS version to be used. If this parameter is not set, the CURL_SSLVERSION_TLSv1_2 version is used. Available options are as follows:
CURL_SSLVERSION_TLSv1_0
CURL_SSLVERSION_TLSv1_1
CURL_SSLVERSION_TLSv1_2
CURL_SSLVERSION_TLSv1_3
The **X-Cipher-List** parameter in **header** specifies the cipher suite list to be used. If this parameter is not specified, the secure cipher suite list is used. Available options are as follows:
- The TLS 1.2 cipher suite list includes the following ciphers:
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,TLS_DSS_RSA_WITH_AES_256_GCM_SHA384,
TLS_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,
TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_128_CCM,
TLS_DHE_RSA_WITH_AES_256_CCM,TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
TLS_PSK_WITH_AES_256_CCM,TLS_DHE_PSK_WITH_AES_128_CCM,
TLS_DHE_PSK_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
TLS_ECDHE_ECDSA_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
- The TLS 1.3 cipher suite list includes the following ciphers:
TLS_AES_128_GCM_SHA256,TLS_AES_256_GCM_SHA384,TLS_CHACHA20_POLY1305_SHA256,TLS_AES_128_CCM_SHA256
- The TLS 1.3 cipher suite list adds the Chinese national cryptographic algorithm:
TLS_SM4_GCM_SM3,TLS_SM4_CCM_SM3 | +| enableMetered | boolean | No| Whether download is allowed on a metered connection. The default value is **false**. In general cases, a mobile data connection is metered, while a Wi-Fi connection is not.
- **true**: allowed
- **false**: not allowed| +| enableRoaming | boolean | No| Whether download is allowed on a roaming network. The default value is **false**.
- **true**: allowed
- **false**: not allowed| +| description | string | No| Description of the download session.| +| filePath7+ | string | No| Path where the downloaded file is stored.
- In the FA model, use [context](js-apis-inner-application-context.md) to obtain the cache directory of the application, for example, **\${featureAbility.getContext().getFilesDir()}/test.txt\**, and store the file in this directory.
- In the stage model, use [AbilityContext](js-apis-inner-application-context.md) to obtain the file path, for example, **\${globalThis.abilityContext.tempDir}/test.txt\**, and store the file in this path.| +| networkType | number | No| Network type allowed for download. The default value is **NETWORK_MOBILE and NETWORK_WIFI**.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000| +| title | string | No| Download task name.| +| background9+ | boolean | No| Whether to enable background task notification so that the download status is displayed in the notification panel. The default value is false.| + + +## DownloadInfo7+ +Defines the download task information, which is the callback parameter of the [getTaskInfo9+](#gettaskinfo9) API. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +| Name| Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| downloadId | number |Yes| ID of the download task.| +| failedReason | number|Yes| Cause of the download failure. The value can be any constant in [Download Error Codes](#download-error-codes).| +| fileName | string |Yes| Name of the downloaded file.| +| filePath | string |Yes| URI of the saved file.| +| pausedReason | number |Yes| Cause of download pause. The value can be any constant in [Causes of Download Pause](#causes-of-download-pause).| +| status | number |Yes| Download task status code. The value can be any constant in [Download Task Status Codes](#download-task-status-codes).| +| targetURI | string |Yes| URI of the downloaded file.| +| downloadTitle | string |Yes| Name of the download task.| +| downloadTotalBytes | number |Yes| Total size of the files to download, in bytes.| +| description | string |Yes| Description of the download task.| +| downloadedBytes | number |Yes| Size of the files downloaded, in bytes.| + +## Action10+ + +Defines action options. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Value | Description | +| -------- | ----- | ----------- | +| DOWNLOAD | 0 | Download. | +| UPLOAD | 1 | Upload. | + + +## Mode10+ + +Defines mode options. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Value | Description | +| ---------- | ----- | ---------------- | +| FOREGROUND | 0 | Foreground task. | + +## Network10+ + +Defines network options. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Value | Description | +| -------- | ----- | ---------------------- | +| ANY | 0 | Network of any type. | +| WIFI | 1 | Wi-Fi network. | +| CELLULAR | 2 | Cellular data network. | + + +## FormItem10+ + +Describes the form item of a task. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| ----- | ------------------------------------------------------------ | --------- | --------------------- | +| name | string | Yes | Form parameter name. | +| value | string \| [FileSpec](#filespec10) \| Array<[FileSpec](#filespec10)> | Yes | Form parameter value. | + + +## Config10+ + +Provides the configuration information of an upload or download task. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ | +| action | [Action](#action10) | Yes | Task action.
- **UPLOAD**
- **DOWNLOAD** | +| url | string | Yes | Resource URL. The value contains a maximum of 2048 characters. | +| title | string | No | Task title. The value contains a maximum of 256 characters. The default value is a null string. | +| description | string | No | Task description. The value contains a maximum of 1024 characters. The default value is a null string. | +| mode | [Mode](#mode10) | No | Task mode. The default mode is foreground .
- For a foreground task, a callback is used for notification. | +| overwrite | boolean | No | Whether to overwrite an existing file during the download. The default value is **false**.
- **true**: Overwrite the existing file.
- **false**: Do not overwrite the existing file. In this case, the download fails. | +| method | string | No | Standard HTTP method for the task. The value can be **GET**, **POST**, or **PUT**, which is case-insensitive.
- If the task is an upload, use **PUT** or **POST**. The default value is **PUT**.
- If the task is a download, use **GET** or **POST**. The default value is **GET**. | +| headers | object | No | HTTP headers to be included in the task.
- If the task is an upload, the default **Content-Type** is **multipart/form-data**.
- If the task is a download, the default **Content-Type** is **application/json**. | +| data | string \| Array<[FormItem](#formitem10)> | No | Task data.
- If the task is a download, the value is a string, typically in JSON format (an object will be converted to a JSON string); the default value is null.
- If the task is an upload, the value is Array<[FormItem](#formitem10)>; the default value is null. | +| saveas | string | No | Path for storing downloaded files. The options are as follows:
- Relative path in the cache folder of the invoker, for example, **"./xxx/yyy/zzz.html"** and **"xxx/yyy/zzz.html"**.
- URI (applicable when the application has the permission to access the URI), for example, **"datashare://bundle/xxx/yyy/zzz.html"**. This option is not supported currently.
The default value is a relative path in the cache folder of the application. | +| network | [Network](#network10) | No | Network used for the task. The default value is **ANY** (Wi-Fi or cellular). | +| metered | boolean | No | Whether the task is allowed on a metered connection. The default value is **false**.
- **true**: The task is allowed on a metered connection.
- **false**: The task is not allowed on a metered connection. | +| roaming | boolean | No | Whether the task is allowed on a roaming network. The default value is **true**.
- **true**: The task is allowed on a roaming network.
- **false**: The task is not allowed on a roaming network. | +| redirect | boolean | No | Whether redirection is allowed. The default value is **true**.
- **true**: Redirection is allowed.
- **false**: Redirection is not allowed. | +| index | number | No | Path index of the task. It is usually used for resumable downloads. The default value is **0**. | +| begins | number | No | File start point of the task. It is usually used for resumable downloads. The default value is **0**. The value is a closed interval.
- If the task is a download, the value is obtained by sending an HTTP range request to read the start position when the server starts to download files.
- If the task is an upload, the value is obtained at the beginning of the upload. | +| ends | number | No | File end point of the task. It is usually used for resumable downloads. The default value is **-1**. The value is a closed interval.
- If the task is a download, the value is obtained by sending an HTTP range request to read the end position when the server starts to download files.
- If the task is an upload, the value is obtained at the end of the upload. | +| precise | boolean | No | - If this parameter is set to **true**, the task fails when the file size cannot be obtained.
- If this parameter is set to **false**, the task continues when the file size is set to **-1**.
The default value is **false**. | +| token | string | No | Token of the task. If the task has a token configured, this token is required for query of the task. The value contains 8 to 2048 bytes. This parameter is left empty by default. | +| extras | object | No | Additional information of the task. This parameter is left empty by default. | +| proxy20+ | string | No| Proxy address. The value contains a maximum of 512 characters.
It is in the format of http://\:\. By default, this parameter is left blank.| + +## State10+ + +Defines the current task status. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Value | Description | +| ----------- | ----- | ------------------------------------------------------------ | +| INITIALIZED | 0x00 | The task is initialized based on the configuration specified in [Config](#config10). | +| WAITING | 0x10 | The task lacks resources for running or the resources for retries do not match the network status. | +| RUNNING | 0x20 | The task is being executed. | +| RETRYING | 0x21 | The task has failed at least once and is being executed again. | +| PAUSED | 0x30 | The task is suspended and will be resumed later. | +| STOPPED | 0x31 | The task is stopped. | +| COMPLETED | 0x40 | The task is complete. | +| FAILED | 0x41 | The task fails. | +| REMOVED | 0x50 | The task is removed. | + + +## Progress10+ + +Describes the data structure of the task progress. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| --------- | ------------------- | --------- | ------------------------------------------------------------ | +| state | [State](#state10) | Yes | Current task status. | +| index | number | Yes | Index of the file that is being processed in the task. | +| processed | number | Yes | Size of processed data in the current file in the task, in bytes. | +| sizes | Array<number> | Yes | Size of files in the task, in bytes. | +| extras | object | No | Extra information of the task, for example, the header of the response from the server. | + + +## Faults10+ + +Defines the cause of a task failure. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Value | Description | +| ------------ | ----- | ------------------------------------------------------------ | +| OTHERS | 0xFF | Other fault. | +| DISCONNECTED | 0x00 | Network disconnection. | +| TIMEOUT | 0x10 | Timeout. | +| PROTOCOL | 0x20 | Protocol error, for example, an internal server error (500) or a data range that cannot be processed (416). | +| FSIO | 0x40 | File system I/O error, for example, an error that occurs during the open, search, read, write, or close operation. | + + +## Filter10+ + +Defines the filter criteria. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| ------ | ------------------- | --------- | ------------------------------------------------------------ | +| before | number | No | Unix timestamp of the end time, in milliseconds. The default value is the invoking time. | +| after | number | No | Unix timestamp of the start time, in milliseconds. The default value is the invoking time minus 24 hours. | +| state | [State](#state10) | No | Task state. | +| action | [Action](#action10) | No | Task action.
- **UPLOAD**
- **DOWNLOAD** | +| mode | [Mode](#mode10) | No | Task mode.
- **FOREGROUND** | + +## TaskInfo10+ + +Defines the data structure of the task information for query. The fields available vary depending on the query type. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ | +| saveas | string | No | Path for storing downloaded files. The options are as follows:
- Relative path in the cache folder of the invoker, for example, **"./xxx/yyy/zzz.html"** and **"xxx/yyy/zzz.html"**.
- URI (applicable when the application has the permission to access the URI), for example, **"datashare://bundle/xxx/yyy/zzz.html"**. This option is not supported currently.
The default value is a relative path in the cache folder of the application. | +| url | string | No | Task URL.
- It can be obtained through [request.agent.show10+](#requestagentshow10-1), [request.agent.touch10+](#requestagenttouch10-1), or [request.agent.query10+](#requestagentquery10-1). When [request.agent.query10+](#requestagentquery10-1) is used, an empty string is returned. | +| data | string \| Array<[FormItem](#formitem10)> | No | Task value.
- It can be obtained through [request.agent.show10+](#requestagentshow10-1), [request.agent.touch10+](#requestagenttouch10-1), or [request.agent.query10+](#requestagentquery10-1). When [request.agent.query10+](#requestagentquery10-1) is used, an empty string is returned. | +| tid | string | Yes | Task ID. | +| title | string | Yes | Task title. | +| description | string | Yes | Task description. | +| action | [Action](#action10) | Yes | Task action.
- **UPLOAD**
- **DOWNLOAD** | +| mode | [Mode](#mode10) | Yes | Task mode.
- **FOREGROUND** | +| mimeType | string | Yes | MIME type in the task configuration. | +| progress | [Progress](#progress10) | Yes | Task progress. | +| ctime | number | Yes | Unix timestamp when the task is created, in milliseconds. The value is generated by the system of the current device.
Note: When [request.agent.search10+](#requestagentsearch10-1) is used for query, this value must be within the range of [after,before] for the task ID to be obtained. For details about **before** and **after**, see [Filter](#filter10). | +| mtime | number | Yes | Unix timestamp when the task state changes, in milliseconds. The value is generated by the system of the current device. | +| faults | [Faults](#faults10) | Yes | Failure cause of the task.
- **OTHERS**: other fault.
- **DISCONNECT**: network disconnection.
- **TIMEOUT**: timeout.
- **PROTOCOL**: protocol error.
- **FSIO**: file system I/O error. | +| reason | string | Yes | Reason why the task is waiting, failed, stopped, or paused. | +| extras | string | No | Extra information of the task | +| priority20+ | number | Yes| Task priority. The priority of a foreground task is higher than that of a background task. For tasks in the same mode, a smaller value indicates a higher priority.| + +## HttpResponse20+ +Describes the data structure of the task response header. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| version | string | Yes| HTTP version.| +| statusCode | number | Yes| HTTP response status code.| +| reason | string | Yes| HTTP response cause.| +| headers | Map<string, Array<string>> | Yes| HTTP response header.| + +## BroadcastEvent20+ + +Defines a custom system event. You can use a common event API to obtain the event. +The upload and download SA has the ohos.permission.SEND_TASK_COMPLETE_EVENT permission. You can configure the level-2 configuration file to which the metadata of an event points to intercept other event senders. + +Use the **CommonEventData** type to transmit data related to common events. The members in **CommonEventData** are different from those described in [CommonEventData](js-apis-inner-commonEvent-commonEventData.md). Specifically, **CommonEventData.code** indicates the task status, which is **0x40 COMPLETE** or **0x41 FAILED**, and **CommonEventData.data** indicates the task ID. + + +For details about how to obtain the event configuration and configure the level-2 configuration file, see [Subscribing to Common Events in Static Mode (for System Applications Only)](../../basic-services/common-event/common-event-static-subscription.md). + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Value| Description | +| -------- | ------- |-----------| +| COMPLETE | 'ohos.request.event.COMPLETE' | Task completion event. The returned event code can be **0x40** or **0x41**, depending on whether the task is successful or fails.| + + +## Task10+ + +Implements an upload or download task. Before using this API, you must obtain a **Task** object, from a promise through [request.agent.create10+](#requestagentcreate10-1) or from a callback through [request.agent.create10+](#requestagentcreate10). + +### Attributes + +Task attributes include the task ID and task configuration. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| ------ | ------------------- | --------- | ------------------------------------------------------------ | +| tid | string | Yes | Task ID, which is unique in the system and is automatically generated by the system. | +| config | [Config](#config10) | Yes | Task configuration. | + + +### on('progress')10+ + +on(event: 'progress', callback: (progress: Progress) => void): void + +Subscribes to foreground task progress changes. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'progress'**, indicating the task progress. | +| callback | function | Yes | Callback used to return the data structure of the task progress. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + mimeType: "application/octet-stream", + path: "./taskOnTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task progress.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('progress', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('completed')10+ + +on(event: 'completed', callback: (progress: Progress) => void): void + +Subscribes to the foreground task completion event. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'completed'**, indicating task completion. | +| callback | function | Yes | Callback used to return the data structure of the task progress. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + mimeType: "application/octet-stream", + path: "./taskOnTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task completed.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('completed', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('failed')10+ + +on(event: 'failed', callback: (progress: Progress) => void): void + +Subscribes to the foreground task failure event. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'failed'**, indicating task failure. | +| callback | function | Yes | Callback used to return the data structure of the task progress. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + mimeType: "application/octet-stream", + path: "./taskOnTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task failed.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('failed', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('response')20+ + +on(event: 'response', callback: Callback<HttpResponse>): void + +Subscribes to task response headers. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
- **'response'**: task response.| +| callback | Callback<[HttpResponse](#httpresponse12)> | Yes| Callback used to return the data structure of the task response header.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + path: "./taskOnTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (response: request.agent.HttpResponse) => { + console.info('upload task response.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('response', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('pause')20+ + +on(event: 'pause', callback: (progress: [Progress](#progress10)) => void): void + +Subscribes to task pause events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
- **'pause'**: task pause.| +| callback | function | Yes| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + path: "./taskOnTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task pause.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('pause', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('resume')20+ + +on(event: 'resume', callback: (progress: [Progress](#progress10)) => void): void + +Subscribes to task resume events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
- **'resume'**: task resume.| +| callback | function | Yes| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + path: "./taskOnTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task resume.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('resume', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.resume(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('remove')20+ + +on(event: 'remove', callback: (progress: [Progress](#progress10)) => void): void + +Subscribes to task removal events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
- **'remove'**: task removal.| +| callback | function | Yes| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + path: "./taskOnTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task remove.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('remove', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + request.agent.remove(task.tid); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + + + +### off('progress')10+ + +off(event: 'progress', callback?: (progress: Progress) => void): void + +Unsubscribes from foreground task progress changes. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'progress'**, indicating the task progress. | +| callback | function | No | Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + mimeType: "application/octet-stream", + path: "./taskOffTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task progress.'); +}; +let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task progress.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('progress', createOffCallback1); + task.on('progress', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('progress', createOffCallback1); + // Unsubscribe from all callbacks of foreground task progress changes. + task.off('progress'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('completed')10+ + +off(event: 'completed', callback?: (progress: Progress) => void): void + +Unsubscribes from the foreground task completion event. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'completed'**, indicating task completion. | +| callback | function | No | Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + mimeType: "application/octet-stream", + path: "./taskOffTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task completed.'); +}; +let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task completed.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('completed', createOffCallback1); + task.on('completed', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('completed', createOffCallback1); + // Unsubscribe from all callbacks of the foreground task completion event. + task.off('completed'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('failed')10+ + +off(event: 'failed', callback?: (progress: Progress) => void): void + +Unsubscribes from the foreground task failure event. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'failed'**, indicating task failure. | +| callback | function | No | Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + mimeType: "application/octet-stream", + path: "./taskOffTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task failed.'); +}; +let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task failed.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('failed', createOffCallback1); + task.on('failed', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('failed', createOffCallback1); + // Unsubscribe from all callbacks of the foreground task failure event. + task.off('failed'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('response')20+ + +off(event: 'response', callback?: Callback<HttpResponse>): void + +Unsubscribes from task response headers. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to unsubscribe from.
- **response**: task response.| +| callback | Callback<[HttpResponse](#httpresponse12)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + path: "./taskOffTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOffCallback1 = (progress: request.agent.HttpResponse) => { + console.info('upload task response.'); + }; + let createOffCallback2 = (progress: request.agent.HttpResponse) => { + console.info('upload task response.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('response', createOffCallback1); + task.on('response', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('response', createOffCallback1); + // Unsubscribe from all callbacks of the task removal event. + task.off('response'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('pause')20+ + +off(event: 'pause', callback?: (progress: [Progress](#progress10)) => void): void + +Unsubscribes from the foreground task pause event. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to unsubscribe from.
- **'pause'**: task pause.| +| callback | function | No| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + path: "./taskOffTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task pause.'); + }; + let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task pause.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('pause', createOffCallback1); + task.on('pause', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('pause', createOffCallback1); + // Unsubscribe from all callbacks of the foreground task pause event. + task.off('pause'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('resume')20+ + +off(event: 'resume', callback?: (progress: [Progress](#progress10)) => void): void + +Unsubscribes from the foreground task resume event. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to unsubscribe from.
- **'resume'**: task resume.| +| callback | function | No| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + path: "./taskOffTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task resume.'); + }; + let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task resume.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('resume', createOffCallback1); + task.on('resume', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('resume', createOffCallback1); + // Unsubscribe from all callbacks of the foreground task resume event. + task.off('resume'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('remove')20+ + +off(event: 'remove', callback?: (progress: [Progress](#progress10)) => void): void + +Unsubscribes from the task removal event. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to unsubscribe from.
- **'remove'**: task removal.| +| callback | function | No| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + path: "./taskOffTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task remove.'); + }; + let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task remove.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('remove', createOffCallback1); + task.on('remove', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('remove', createOffCallback1); + // Unsubscribe from all callbacks of the task removal event. + task.off('remove'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### start10+ + +start(callback: AsyncCallback<void>): void + +Starts this task. This API cannot be used to start an initialized task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| callback | function | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```ts +let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStartTest', + description: 'Sample code for start the download task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.start((err: BusinessError) => { + if (err) { + console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in starting a download task.`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### start10+ + +start(): Promise<void> + +Starts this task. This API cannot be used to start an initialized task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```ts +let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStartTest', + description: 'Sample code for start the download task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.start().then(() => { + console.info(`Succeeded in starting a download task.`); + }).catch((err: BusinessError) => { + console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### pause20+ + +pause(callback: AsyncCallback<void>): void + +Pauses a task that is waiting, running, or retrying. A paused task can be resumed by [resume](#resume10). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | Task service ability error. | +| 21900007 | Operation with wrong task state. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskPauseTest', + description: 'Sample code for pause the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause((err: BusinessError) => { + if (err) { + console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in pausing a download task. `); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +### pause20+ + +pause(): Promise<void> + +Pauses a task that is waiting, running, or retrying. A paused task can be resumed by [resume](#resume10). This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | Task service ability error. | +| 21900007 | Operation with wrong task state. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskPauseTest', + description: 'Sample code for pause the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause().then(() => { + console.info(`Succeeded in pausing a download task. `); + }).catch((err: BusinessError) => { + console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` +### resume20+ + +resume(callback: AsyncCallback<void>): void + +Resumes a paused task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission denied. | +| 13400003 | Task service ability error. | +| 21900007 | Operation with wrong task state. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskResumeTest', + description: 'Sample code for resume the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.resume((err: BusinessError) => { + if (err) { + console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in resuming a download task. `); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +### resume20+ + +resume(): Promise<void> + +Resumes a paused task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission denied. | +| 13400003 | Task service ability error. | +| 21900007 | Operation with wrong task state. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskResumeTest', + description: 'Sample code for resume the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.resume().then(() => { + console.info(`Succeeded in resuming a download task. `); + }).catch((err: BusinessError) => { + console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +### stop10+ + +stop(callback: AsyncCallback<void>): void + +Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| callback | function | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```ts +let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStopTest', + description: 'Sample code for stop the download task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.stop((err: BusinessError) => { + if (err) { + console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in stopping a download task. `); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + + +### stop10+ + +stop(): Promise<void> + +Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```ts +let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStopTest', + description: 'Sample code for stop the download task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.stop().then(() => { + console.info(`Succeeded in stopping a download task. `); + }).catch((err: BusinessError) => { + console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +## request.agent.create10+ + +create(context: BaseContext, config: Config, callback: AsyncCallback<Task>): void + +Creates an upload or download task and adds it to the queue. An application can create a maximum of 10 unfinished tasks. This API uses an asynchronous callback to return the result. + + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| config | [Config](#config10) | Yes | Task configuration. | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes | Application-based context. | +| callback | AsyncCallback<[Task](#task10)> | Yes | Callback used to return the configuration about the created task. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------------------------- | +| 13400001 | file operation error. | +| 13400003 | task service ability error. | +| 21900004 | application task queue full error. | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "createTest", + value: { + filename: "createTest.avi", + mimeType: "application/octet-stream", + path: "./createTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'createTest', + description: 'Sample code for create task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config, (err: BusinessError, task: request.agent.Task) => { + if (err) { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in creating a download task. result: ${task.config}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +## request.agent.create10+ + +create(context: BaseContext, config: Config): Promise<Task> + +Creates an upload or download task and adds it to the queue. An application can create a maximum of 10 unfinished tasks. This API uses a promise to return the result. + + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------------------------- | --------- | -------------------------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes | Application-based context. | +| config | [Config](#config10) | Yes | Task configuration. | + +**Return value** + +| Type | Description | +| ------------------------------ | ------------------------------------------------------------ | +| Promise<[Task](#task10)> | Promise used to return the configuration about the created task. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------------------------- | +| 13400001 | file operation error. | +| 13400003 | task service ability error. | +| 21900004 | application task queue full error. | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "createTest", + value: { + filename: "createTest.avi", + mimeType: "application/octet-stream", + path: "./createTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'createTest', + description: 'Sample code for create task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + console.info(`Succeeded in creating a download task. result: ${task.config}`); +}).catch((err) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +## request.agent.remove10+ + +remove(id: string, callback: AsyncCallback<void>): void + +Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| id | string | Yes | Task ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.remove("123456", (err: BusinessError) => { + if (err) { + console.error(`Failed to removing a download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in creating a download task.`); +}); + ``` + + +## request.agent.remove10+ + +remove(id: string): Promise<void> + +Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ----------- | +| id | string | Yes | Task ID. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.remove("123456").then(() => { + console.info(`Succeeded in removing a download task. `); +}).catch((err: BusinessError) => { + console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + + +## request.agent.show10+ + +show(id: string, callback: AsyncCallback<TaskInfo>): void + +Shows the task details based on the task ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------------- | --------- | ------------------------------------- | +| id | string | Yes | Task ID. | +| callback | AsyncCallback<[TaskInfo](#taskinfo10)> | Yes | Callback used to return task details. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.show("123456", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { + if (err) { + console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in showing a upload task.`); +}); + ``` + + +## request.agent.show10+ + +show(id: string): Promise<TaskInfo> + +Queries a task details based on the task ID. This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ----------- | +| id | string | Yes | Task ID. | + +**Return value** + +| Type | Description | +| -------------------------------------- | -------------------------------------------- | +| Promise<[TaskInfo](#taskinfo10)> | Promise Promise used to return task details. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.show("123456").then((taskInfo: request.agent.TaskInfo) => { + console.info(`Succeeded in showing the upload task.`); +}).catch((err: BusinessError) => { + console.error(`Failed to show the upload task. Code: ${err.code}, message: ${err.message}`); +}); + ``` + + +## request.agent.touch10+ + +touch(id: string, token: string, callback: AsyncCallback<TaskInfo>): void + +Queries the task details based on the task ID and token. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------------- | --------- | ------------------------------------- | +| id | string | Yes | Task ID. | +| token | string | Yes | Token for task query. | +| callback | AsyncCallback<[TaskInfo](#taskinfo10)> | Yes | Callback used to return task details. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.touch("123456", "token", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { + if (err) { + console.error(`Failed to touch an upload task. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in touching an upload task.`); +}); + ``` + + +## request.agent.touch10+ + +touch(id: string, token: string): Promise<TaskInfo> + +Queries the task details based on the task ID and token. This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | --------- | --------------------- | +| id | string | Yes | Task ID. | +| token | string | Yes | Token for task query. | + +**Return value** + +| Type | Description | +| -------------------------------------- | -------------------------------------------- | +| Promise<[TaskInfo](#taskinfo10)> | Promise Promise used to return task details. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.touch("123456", "token").then((taskInfo: request.agent.TaskInfo) => { + console.info(`Succeeded in touching a upload task. `); +}).catch((err: BusinessError) => { + console.error(`Failed to touch an upload task. Code: ${err.code}, message: ${err.message}`); +}); + ``` + +## request.agent.search10+ + +search(callback: AsyncCallback<Array<string>>): void + +Searches for task IDs based on [Filter](#filter10). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ---------------------------------------- | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return task ID matches. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | + +**Example** + + ```ts +request.agent.search((err: BusinessError, data: Array) => { + if (err) { + console.error(`Upload task search failed. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Upload task search succeeded. `); +}); + ``` + + +## request.agent.search10+ + +search(filter?: Filter): Promise<Array<string>> + +Searches for task IDs based on [Filter](#filter10). This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------------------- | --------- | ---------------- | +| filter | [Filter](#filter10) | No | Filter criteria. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ----------------------------------------------- | +| Promise<Array<string>> | Promise Promise used to return task ID matches. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | + +**Example** + + ```ts +let filter: request.agent.Filter = { + bundle: "com.example.myapplication", + action: request.agent.Action.UPLOAD, + mode: request.agent.Mode.FOREGROUND +} +request.agent.search(filter).then((data: Array) => { + console.info(`Upload task search succeeded. `); +}).catch((err: BusinessError) => { + console.error(`Upload task search failed. Code: ${err.code}, message: ${err.message}`); +}); + ``` + + \ No newline at end of file diff --git a/arkuix_zh/js-apis-data-preferences.md b/arkuix_zh/js-apis-data-preferences.md new file mode 100644 index 0000000000000000000000000000000000000000..8f8d7fe1274c5115f2850bd92a5062977514cef2 --- /dev/null +++ b/arkuix_zh/js-apis-data-preferences.md @@ -0,0 +1,1743 @@ +# @ohos.data.preferences (用户首选项) + +用户首选项为应用提供Key-Value键值型的数据处理能力,支持应用持久化轻量级数据,并对其修改和查询。 + +数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型以及这3种类型的数组类型。 + + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +```ts +import data_preferences from '@ohos.data.preferences'; +``` + +## 常量 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| ---------------- | -------- | ---- | ---- | --------------------------------------- | +| MAX_KEY_LENGTH | number | 是 | 否 | Key的最大长度限制为80个字节。 | +| MAX_VALUE_LENGTH | number | 是 | 否 | Value的最大长度限制为8192个字节。 | + + +## data_preferences.getPreferences + +getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void + +获取Preferences实例,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | +| name | string | 是 | Preferences实例的名称。 | +| callback | AsyncCallback<[Preferences](#preferences)> | 是 | 回调函数。当获取Preferences实例成功,err为undefined,返回Preferences实例;否则err为错误对象。 | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base'; +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences | null = null; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, val: data_preferences.Preferences) => { + if (err) { + console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + return; + } + preferences = val; + console.info("Succeeded in getting preferences."); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.getPreferences + +getPreferences(context: Context, name: string): Promise<Preferences> + +获取Preferences实例,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | +| name | string | 是 | Preferences实例的名称。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------ | ---------------------------------- | +| Promise<[Preferences](#preferences)> | Promise对象,返回Preferences实例。 | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences | null = null; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let promise = data_preferences.getPreferences(this.context, 'myStore'); + promise.then((object: data_preferences.Preferences) => { + preferences = object; + console.info("Succeeded in getting preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.getPreferences10+ + +getPreferences(context: Context, options: Options, callback: AsyncCallback<Preferences>): void + +获取Preferences实例,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | +| callback | AsyncCallback<[Preferences](#preferences)> | 是 | 回调函数。当获取Preferences实例成功,err为undefined,返回Preferences实例;否则err为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences | null = null; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.getPreferences(this.context, options, (err: BusinessError, val: data_preferences.Preferences) => { + if (err) { + console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + return; + } + preferences = val; + console.info("Succeeded in getting preferences."); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.getPreferences10+ + +getPreferences(context: Context, options: Options): Promise<Preferences> + +获取Preferences实例,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------------------- | ---------------------------------- | +| Promise<[Preferences](#preferences)> | Promise对象,返回Preferences实例。 | + +**错误码:** + +以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences | null = null; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.getPreferences(this.context, options); + promise.then((object: data_preferences.Preferences) => { + preferences = object; + console.info("Succeeded in getting preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to get preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.getPreferencesSync10+ + +getPreferencesSync(context: Context, options: Options): Preferences + +获取Preferences实例,此为同步接口。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | --------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------------- | --------------------- | +| [Preferences](#preferences) | 返回Preferences实例。 | + +**错误码:** + +以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------- | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +let preferences: data_preferences.Preferences | null = null; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + preferences = data_preferences.getPreferencesSync(this.context, options); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.deletePreferences + +deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void + +从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用callback异步回调。 + +调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | +| name | string | 是 | Preferences实例的名称。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当移除成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------| +| 15500010 | Failed to delete preferences file. | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + data_preferences.deletePreferences(this.context, 'myStore', (err: BusinessError) => { + if (err) { + console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in deleting preferences." ); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.deletePreferences + +deletePreferences(context: Context, name: string): Promise<void> + +从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用Promise异步回调。 + +调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | +| name | string | 是 | Preferences实例的名称。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------| +| 15500010 | Failed to delete preferences file. | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try{ + let promise = data_preferences.deletePreferences(this.context, 'myStore'); + promise.then(() => { + console.info("Succeeded in deleting preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.deletePreferences10+ + +deletePreferences(context: Context, options: Options, callback: AsyncCallback<void>): void + +从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用callback异步回调。 + +调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当移除成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------- | +| 15500010 | Failed to delete preferences file. | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.deletePreferences(this.context, options, (err: BusinessError) => { + if (err) { + console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in deleting preferences." ); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.deletePreferences10+ + +deletePreferences(context: Context, options: Options): Promise<void> + +从缓存中移出指定的Preferences实例,若Preferences实例有对应的持久化文件,则同时删除其持久化文件。使用Promise异步回调。 + +调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------- | +| 15500010 | Failed to delete preferences file. | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try{ + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.deletePreferences(this.context, options); + promise.then(() => { + console.info("Succeeded in deleting preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to delete preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.removePreferencesFromCache + +removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback<void>): void + +从缓存中移出指定的Preferences实例,使用callback异步回调。 + +应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 + +调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | +| name | string | 是 | Preferences实例的名称。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当移除成功,err为undefined,否则为错误对象。 | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + data_preferences.removePreferencesFromCache(this.context, 'myStore', (err: BusinessError) => { + if (err) { + console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in removing preferences."); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} + +``` + +## data_preferences.removePreferencesFromCache + +removePreferencesFromCache(context: Context, name: string): Promise<void> + +从缓存中移出指定的Preferences实例,使用Promise异步回调。 + +应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 + +调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | +| name | string | 是 | Preferences实例的名称。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let promise = data_preferences.removePreferencesFromCache(this.context, 'myStore'); + promise.then(() => { + console.info("Succeeded in removing preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.removePreferencesFromCacheSync10+ + +removePreferencesFromCacheSync(context: Context, name: string): void + +从缓存中移出指定的Preferences实例,此为同步接口。 + +应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 + +调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-context.md)。 | +| name | string | 是 | Preferences实例的名称。 | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + data_preferences.removePreferencesFromCacheSync(this.context, 'myStore'); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.removePreferencesFromCache10+ + +removePreferencesFromCache(context: Context, options: Options, callback: AsyncCallback<void>): void + +从缓存中移出指定的Preferences实例,使用callback异步回调。 + +应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 + +调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当移除成功,err为undefined,否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.removePreferencesFromCache(this.context, options, (err: BusinessError) => { + if (err) { + console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in removing preferences."); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.removePreferencesFromCache10+ + +removePreferencesFromCache(context: Context, options: Options): Promise<void> + +从缓存中移出指定的Preferences实例,使用Promise异步回调。 + +应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 + +调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ---------------- | ---- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import { BusinessError } from '@ohos.base' +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + let promise = data_preferences.removePreferencesFromCache(this.context, options); + promise.then(() => { + console.info("Succeeded in removing preferences."); + }).catch((err: BusinessError) => { + console.error("Failed to remove preferences. code =" + err.code + ", message =" + err.message); + }) + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## data_preferences.removePreferencesFromCacheSync10+ + +removePreferencesFromCacheSync(context: Context, options: Options):void + +从缓存中移出指定的Preferences实例,此为同步接口。 + +应用首次调用[getPreferences](#data_preferencesgetpreferences)接口获取某个Preferences实例后,该实例会被会被缓存起来,后续再次[getPreferences](#data_preferencesgetpreferences)时不会再次从持久化文件中读取,直接从缓存中获取Preferences实例。调用此接口移出缓存中的实例之后,再次getPreferences将会重新读取持久化文件,生成新的Preferences实例。 + +调用该接口后,不建议再使用旧的Preferences实例进行数据操作,否则会出现数据一致性问题,应将Preferences实例置为null,系统将会统一回收。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | --------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| options | [Options](#options10) | 是 | 与Preferences实例相关的配置选项。 | + +**错误码:** + +以下错误码的详细介绍请参见[用户首选项错误码](../errorcodes/errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------- | +| 15501001 | Only supported in stage mode. | +| 15501002 | The data group id is not valid. | + +**示例:** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import window from '@ohos.window'; + +class EntryAbility extends UIAbility { + onWindowStageCreate(windowStage: window.WindowStage) { + try { + let options: data_preferences.Options = { name: 'myStore', dataGroupId:'myId' }; + data_preferences.removePreferencesFromCacheSync(this.context, options); + } catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to remove preferences. code =" + code + ", message =" + message); + } + } +} +``` + +## Options10+ + +Preferences实例配置选项。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +| 名称 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| name | string | 是 | Preferences实例的名称。 | +| dataGroupId | string | 否 | 应用组ID,需要向应用市场获取。
**模型约束:** 此属性仅在Stage模型下可用。
从API version 10开始,支持此可选参数。指定在此dataGroupId对应的沙箱路径下创建Preferences实例,当此参数不填时,默认在本应用沙箱目录下创建Preferences实例。 | + +## Preferences + +首选项实例,提供获取和修改存储数据的接口。 + +下列接口都需先使用[data_preferences.getPreferences](#data_preferencesgetpreferences)获取到Preferences实例,再通过此实例调用对应接口。 + + +### get + +get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void + +从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| key | string | 是 | 要获取的存储Key名称,不能为空。 | +| defValue | [ValueType](#valuetype) | 是 | 默认返回值。支持number、string、boolean、Array\、Array\、Array\类型。 | +| callback | AsyncCallback<[ValueType](#valuetype)> | 是 | 回调函数。当获取成功时,err为undefined,data为键对应的值;否则err为错误对象。 | + +**示例:** + +```ts +try { + preferences.get('startup', 'default', (err: BusinessError, val: data_preferences.ValueType) => { + if (err) { + console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in getting value of 'startup'. val: " + val); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); +} +``` + +### get + +get(key: string, defValue: ValueType): Promise<ValueType> + +从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + + **参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | 是 | 要获取的存储Key名称,不能为空。 | +| defValue | [ValueType](#valuetype) | 是 | 默认返回值。支持number、string、boolean、Array\、Array\、Array\类型。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------- | ----------------------------- | +| Promise<[ValueType](#valuetype)> | Promise对象,返回键对应的值。 | + +**示例:** + +```ts +try { + let promise = preferences.get('startup', 'default'); + promise.then((data: data_preferences.ValueType) => { + console.info("Succeeded in getting value of 'startup'. Data: " + data); + }).catch((err: BusinessError) => { + console.error("Failed to get value of 'startup'. code =" + err.code + ", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); +} +``` + +### getSync10+ + +getSync(key: string, defValue: ValueType): ValueType + +从缓存的Preferences实例中获取键对应的值,如果值为null或者非默认值类型,返回默认数据defValue,此为同步接口。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | 是 | 要获取的存储Key名称,不能为空。 | +| defValue | [ValueType](#valuetype) | 是 | 默认返回值。支持number、string、boolean、Array\、Array\、Array\类型。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------- | ----------------------------- | +| [ValueType](#valuetype) | 返回键对应的值。 | + +**示例:** + +```ts +try { + let value: data_preferences.ValueType = preferences.getSync('startup', 'default'); + console.info("Succeeded in getting value of 'startup'. Data: " + value); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get value of 'startup'. code =" + code + ", message =" + message); +} +``` + +### getAll + +getAll(callback: AsyncCallback<Object>): void; + +从缓存的Preferences实例中获取所有键值数据。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<Object> | 是 | 回调函数。当获取成功,err为undefined,value为所有键值数据;否则err为错误对象。 | + +**示例:** + +```ts +// 由于ArkTS中无Object.keys,且无法使用for..in... +// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 +function getObjKeys(obj: Object): string[] { + let keys = Object.keys(obj); + return keys; +} + +try { + preferences.getAll((err: BusinessError, value: Object) => { + if (err) { + console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); + return; + } + let allKeys = getObjKeys(value); + console.info("getAll keys = " + allKeys); + console.info("getAll object = " + JSON.stringify(value)); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get all key-values. code =" + code + ", message =" + message); +} +``` + +### getAll + +getAll(): Promise<Object> + +从缓存的Preferences实例中获取所有键值数据。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------------------------------------------- | +| Promise<Object> | Promise对象,返回含有所有键值数据。 | + +**示例:** + +```ts +// 由于ArkTS中无Object.keys,且无法使用for..in... +// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 +function getObjKeys(obj: Object): string[] { + let keys = Object.keys(obj); + return keys; +} + +try { + let promise = preferences.getAll(); + promise.then((value: Object) => { + let allKeys = getObjKeys(value); + console.info('getAll keys = ' + allKeys); + console.info("getAll object = " + JSON.stringify(value)); + }).catch((err: BusinessError) => { + console.error("Failed to get all key-values. code =" + err.code + ", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get all key-values. code =" + code + ", message =" + message); +} +``` + +### getAllSync10+ + +getAllSync(): Object + +从缓存的Preferences实例中获取所有键值数据。,此为同步接口。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**返回值:** + +| 类型 | 说明 | +| --------------------- | ------------------------------------------- | +| Object | 返回含有所有键值数据。 | + +**示例:** + +```ts +// 由于ArkTS中无Object.keys,且无法使用for..in... +// 若报ArkTS问题,请将此方法单独抽离至一个ts文件中并暴露,在需要用到的ets文件中引入使用 +function getObjKeys(obj: Object): string[] { + let keys = Object.keys(obj); + return keys; +} + +try { + let value = preferences.getAllSync(); + let allKeys = getObjKeys(value); + console.info('getAll keys = ' + allKeys); + console.info("getAll object = " + JSON.stringify(value)); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to get all key-values. code =" + code + ", message =" + message); +} +``` + +### put + +put(key: string, value: ValueType, callback: AsyncCallback<void>): void + +将数据写入缓存的Preferences实例中,可通过[flush](#flush)将Preferences实例持久化,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| key | string | 是 | 要修改的存储的Key,不能为空。 | +| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean、Array\、Array\、Array\类型。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当数据写入成功,err为undefined;否则为错误对象。 | + +**示例:** + +```ts +try { + preferences.put('startup', 'auto', (err: BusinessError) => { + if (err) { + console.error("Failed to put value of 'startup'. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in putting value of 'startup'."); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to put value of 'startup'. code =" + code + ", message =" + message); +} +``` + + +### put + +put(key: string, value: ValueType): Promise<void> + +将数据写入缓存的Preferences实例中,可通过[flush](#flush)将Preferences实例持久化,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | 是 | 要修改的存储的Key,不能为空。 | +| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean、Array\、Array\、Array\类型。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```ts +try { + let promise = preferences.put('startup', 'auto'); + promise.then(() => { + console.info("Succeeded in putting value of 'startup'."); + }).catch((err: BusinessError) => { + console.error("Failed to put value of 'startup'. code =" + err.code +", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to put value of 'startup'. code =" + code +", message =" + message); +} +``` + + +### putSync10+ + +putSync(key: string, value: ValueType): void + +将数据写入缓存的Preferences实例中,可通过[flush](#flush)将Preferences实例持久化,此为同步接口。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | 是 | 要修改的存储的Key,不能为空。 | +| value | [ValueType](#valuetype) | 是 | 存储的新值。支持number、string、boolean、Array\、Array\、Array\类型。 | + +**示例:** + +```ts +try { + preferences.putSync('startup', 'auto'); +} catch(err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to put value of 'startup'. code =" + code +", message =" + message); +} +``` + + +### has + +has(key: string, callback: AsyncCallback<boolean>): void + +检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| key | string | 是 | 要检查的存储key名称,不能为空。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。 | + +**示例:** + +```ts +try { + preferences.has('startup', (err: BusinessError, val: boolean) => { + if (err) { + console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); + return; + } + if (val) { + console.info("The key 'startup' is contained."); + } else { + console.info("The key 'startup' dose not contain."); + } + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); +} +``` + + +### has + +has(key: string): Promise<boolean> + +检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------- | +| key | string | 是 | 要检查的存储key名称,不能为空。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise对象。返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。 | + +**示例:** + +```ts +try { + let promise = preferences.has('startup'); + promise.then((val: boolean) => { + if (val) { + console.info("The key 'startup' is contained."); + } else { + console.info("The key 'startup' dose not contain."); + } + }).catch((err: BusinessError) => { + console.error("Failed to check the key 'startup'. code =" + err.code + ", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); +} +``` + + +### hasSync10+ + +hasSync(key: string): boolean + +检查缓存的Preferences实例中是否包含名为给定Key的存储键值对,此为同步接口。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------- | +| key | string | 是 | 要检查的存储key名称,不能为空。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------- | ------------------------------------------------------------ | +| boolean | 返回Preferences实例是否包含给定key的存储键值对,true表示存在,false表示不存在。 | + +**示例:** + +```ts +try { + let isExist: boolean = preferences.hasSync('startup'); + if (isExist) { + console.info("The key 'startup' is contained."); + } else { + console.info("The key 'startup' dose not contain."); + } +} catch(err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to check the key 'startup'. code =" + code + ", message =" + message); +} +``` + + +### delete + +delete(key: string, callback: AsyncCallback<void>): void + +从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过[flush](#flush)将Preferences实例持久化,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| key | string | 是 | 要删除的存储Key名称,不能为空。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当删除成功,err为undefined;否则为错误对象。 | + +**示例:** + +```ts +try { + preferences.delete('startup', (err: BusinessError) => { + if (err) { + console.error("Failed to delete the key 'startup'. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in deleting the key 'startup'."); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete the key 'startup'. code =" + code + ", message =" + message); +} +``` + + +### delete + +delete(key: string): Promise<void> + +从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过[flush](#flush)将Preferences实例持久化,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------- | +| key | string | 是 | 要删除的存储key名称,不能为空。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```ts +try { + let promise = preferences.delete('startup'); + promise.then(() => { + console.info("Succeeded in deleting the key 'startup'."); + }).catch((err: BusinessError) => { + console.error("Failed to delete the key 'startup'. code =" + err.code +", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message); +} +``` + + +### deleteSync10+ + +deleteSync(key: string): void + +从缓存的Preferences实例中删除名为给定Key的存储键值对,可通过[flush](#flush)将Preferences实例持久化,此为同步接口。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------------------- | +| key | string | 是 | 要删除的存储key名称,不能为空。 | + +**示例:** + +```ts +try { + preferences.deleteSync('startup'); +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to delete the key 'startup'. code =" + code +", message =" + message); +} +``` + + +### flush + +flush(callback: AsyncCallback<void>): void + +将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| callback | AsyncCallback<void> | 是 | 回调函数。当保存成功,err为undefined;否则为错误对象。 | + +**示例:** + +```ts +try { + preferences.flush((err: BusinessError) => { + if (err) { + console.error("Failed to flush. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in flushing."); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); +} +``` + + +### flush + +flush(): Promise<void> + +将缓存的Preferences实例中的数据异步存储到用户首选项的持久化文件中,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```ts +try { + let promise = preferences.flush(); + promise.then(() => { + console.info("Succeeded in flushing."); + }).catch((err: BusinessError) => { + console.error("Failed to flush. code =" + err.code + ", message =" + err.message); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); +} +``` + + +### clear + +clear(callback: AsyncCallback<void>): void + +清除缓存的Preferences实例中的所有数据,可通过[flush](#flush)将Preferences实例持久化,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| callback | AsyncCallback<void> | 是 | 回调函数。当清除成功,err为undefined;否则为错误对象。 | + +**示例:** + +```ts +try { + preferences.clear((err: BusinessError) =>{ + if (err) { + console.error("Failed to clear. code =" + err.code + ", message =" + err.message); + return; + } + console.info("Succeeded in clearing."); + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to clear. code =" + code + ", message =" + message); +} +``` + + +### clear + +clear(): Promise<void> + +清除缓存的Preferences实例中的所有数据,可通过[flush](#flush)将Preferences实例持久化,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```ts +try { + let promise = preferences.clear(); + promise.then(() => { + console.info("Succeeded in clearing."); + }).catch((err: BusinessError) => { + console.error("Failed to clear. code =" + err.code + ", message =" + err.message); + }) +} catch(err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to clear. code =" + code + ", message =" + message); +} +``` + + +### clearSync10+ + +clearSync(): void + +清除缓存的Preferences实例中的所有数据,可通过[flush](#flush)将Preferences实例持久化,此为同步接口。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**示例:** + +```ts +try { + preferences.clearSync(); +} catch(err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to clear. code =" + code + ", message =" + message); +} +``` + + +### on('change') + +on(type: 'change', callback: ( key : string ) => void): void + +订阅数据变更,订阅的Key的值发生变更后,在执行[flush](#flush)方法后,触发callback回调。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ---------------------------------------- | +| type | string | 是 | 事件类型,固定值'change',表示数据变更。 | +| callback | Function | 是 | 回调函数。
key: 发生变化的Key。 | + +**示例:** + +```ts +try { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: data_preferences.Preferences) => { + if (err) { + console.error("Failed to get preferences."); + return; + } + preferences.on('change', (key: string) => { + console.info("The key " + key + " changed."); + }); + preferences.put('startup', 'manual', (err: BusinessError) => { + if (err) { + console.error("Failed to put the value of 'startup'. Cause: " + err); + return; + } + console.info("Succeeded in putting the value of 'startup'."); + + preferences.flush((err: BusinessError) => { + if (err) { + console.error("Failed to flush. Cause: " + err); + return; + } + console.info("Succeeded in flushing."); + }) + }) + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); +} +``` + +### off('change') + +off(type: 'change', callback?: ( key : string ) => void): void + +取消订阅数据变更。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件类型,固定值'change',表示数据变更。 | +| callback | Function | 否 | 需要取消的回调函数,不填写则全部取消。
key: 发生变化的Key。 | + +**示例:** + +```ts + +try { + data_preferences.getPreferences(this.context, 'myStore', (err: BusinessError, preferences: data_preferences.Preferences) => { + if (err) { + console.error("Failed to get preferences."); + return; + } + preferences.on('change', (key: string) => { + console.info("The key " + key + " changed."); + }); + preferences.put('startup', 'auto', (err: BusinessError) => { + if (err) { + console.error("Failed to put the value of 'startup'. Cause: " + err); + return; + } + console.info("Succeeded in putting the value of 'startup'."); + + preferences.flush((err: BusinessError) =>{ + if (err) { + console.error("Failed to flush. Cause: " + err); + return; + } + console.info("Succeeded in flushing."); + }) + preferences.off('change', (key: string) => { + console.info("The key " + key + " changed."); + }); + }) + }) +} catch (err) { + let code = (err as BusinessError).code; + let message = (err as BusinessError).message; + console.error("Failed to flush. code =" + code + ", message =" + message); +} +``` + +### on('dataChange')20+ + +on(type: 'dataChange', keys: Array<string>, callback: Callback<Record<string, ValueType>>): void + +精确订阅数据变更,只有被订阅的key值发生变更后,在执行[flush](#flush)方法后,触发callback回调。 + + > **说明:** + > + > 当调用[removePreferencesFromCache](#preferencesremovepreferencesfromcache)或[deletePreferences](#preferencesdeletepreferences)后,订阅的数据变更会主动取消订阅,在重新[getPreferences](#preferencesgetpreferences)后需要重新订阅数据变更。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件类型,固定值'dataChange',表示精确的数据变更。 | +| keys | Array<string> | 是 | 需要订阅的key集合。 | +| callback | Callback<Record<string, [ValueType](#valuetype)>> | 是 | 回调函数。回调支持返回多个键值对,其中键为发生变更的订阅key,值为变更后的数据:支持number、string、boolean、Array\、Array\、Array\、Uint8Array、object类型。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[用户首选项错误码](errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | +| 15500000 | Inner error. | + +**示例:** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +let observer = (data: Record) => { + for (const keyValue of Object.entries(data)) { + console.info(`observer : ${keyValue}`); + } + console.info("The observer called."); +} +let keys = ['name', 'age']; +dataPreferences.on('dataChange', keys, observer); +dataPreferences.putSync('name', 'xiaohong'); +dataPreferences.putSync('weight', 125); +dataPreferences.flush((err: BusinessError) => { + if (err) { + console.error("Failed to flush. Cause: " + err); + return; + } + console.info("Succeeded in flushing."); +}) +``` + +### off('dataChange')20+ + +off(type: 'dataChange', keys: Array<string>, callback?: Callback<Record<string, ValueType>>): void + +取消精确订阅数据变更。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件类型,固定值'dataChange',表示精确的数据变更。 | +| keys | Array<string> | 是 | 需要取消订阅的key集合,当keys为空数组时,表示取消订阅全部key;当keys为非空数组时,表示只取消订阅key集合中的key。 | +| callback | Callback<Record<string, [ValueType](#valuetype)>> | 否 | 需要取消的回调函数,若callback不填写,表示所有的callback都需要处理;若callback填写,表示只处理该callback。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[用户首选项错误码](errorcode-preferences.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------ | +| 401 | Parameter error. Possible causes:1. Mandatory parameters are left unspecified;2. Incorrect parameter types;3. Parameter verification failed. | +| 15500000 | Inner error. | + +**示例:** + +```ts +import { BusinessError } from '@kit.BasicServicesKit'; + +let observer = (data: Record) => { + for (const keyValue of Object.entries(data)) { + console.info(`observer : ${keyValue}`); + } + console.info("The observer called."); +} +let keys = ['name', 'age']; +dataPreferences.on('dataChange', keys, observer); +dataPreferences.putSync('name', 'xiaohong'); +dataPreferences.putSync('weight', 125); +dataPreferences.flush((err: BusinessError) => { + if (err) { + console.error("Failed to flush. Cause: " + err); + return; + } + console.info("Succeeded in flushing."); +}) +dataPreferences.off('dataChange', keys, observer); +``` + +## ValueType + +用于表示允许的数据字段类型。 + +**系统能力:** SystemCapability.DistributedDataManager.Preferences.Core + +| 类型 | 说明 | +| --------------- | ------------------------------ | +| number | 表示值类型为数字。 | +| string | 表示值类型为字符串。 | +| boolean | 表示值类型为布尔值。 | +| Array\ | 表示值类型为数字类型的数组。 | +| Array\ | 表示值类型为布尔类型的数组。 | +| Array\ | 表示值类型为字符串类型的数组。 | diff --git a/arkuix_zh/js-apis-data-relationalStore.md b/arkuix_zh/js-apis-data-relationalStore.md new file mode 100644 index 0000000000000000000000000000000000000000..4c44c26ca479c671b6351c80b1849f1386207634 --- /dev/null +++ b/arkuix_zh/js-apis-data-relationalStore.md @@ -0,0 +1,5233 @@ +# @ohos.data.relationalStore (关系型数据库) + +关系型数据库(Relational Database,RDB)是一种基于关系模型来管理数据的数据库。关系型数据库基于SQLite组件提供了一套完整的对本地数据库进行管理的机制,对外提供了一系列的增、删、改、查等接口,也可以直接运行用户输入的SQL语句来满足复杂的场景需要。不支持Worker线程。 + +该模块提供以下关系型数据库相关的常用功能: + +- [RdbPredicates](#rdbpredicates): 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。 +- [RdbStore](#rdbstore):提供管理关系数据库(RDB)方法的接口。 +- [ResultSet](#resultset):提供用户调用关系型数据库查询接口之后返回的结果集合。 + +> **说明:** +> +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```ts +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](js-apis-inner-application-uiAbilityContext.md)。 | +| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | 是 | 指定callback回调函数,返回RdbStore对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800011 | Failed to open database by database corrupted. | +| 14800000 | Inner error. | + +**Stage模型示例:** +```ts +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](js-apis-inner-application-uiAbilityContext.md)。 | +| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | + +**返回值**: + +| 类型 | 说明 | +| ----------------------------------------- | --------------------------------- | +| Promise<[RdbStore](#rdbstore)> | Promise对象。返回RdbStore对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800011 | Failed to open database by database corrupted. | +| 14800000 | Inner error. | + +**Stage模型示例:** + +```ts +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](js-apis-inner-application-uiAbilityContext.md)。 | +| name | string | 是 | 数据库名称。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800000 | Inner error. | + +**Stage模型示例:** + +```ts +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](js-apis-inner-application-uiAbilityContext.md)。 | +| name | string | 是 | 数据库名称。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------------------------------------------- | +| 14800010 | Failed to open or delete database by invalid database path. | +| 14800000 | Inner error. | + +**Stage模型示例:** + +```ts +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 + +使用指定的数据库文件配置删除数据库,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码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模型示例:** + +```ts +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\ + +使用指定的数据库文件配置删除数据库,使用Promise异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | --------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | 是 | 应用的上下文。
Stage模型的应用Context定义见[Context](js-apis-inner-application-uiAbilityContext.md)。 | +| config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码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模型示例:** + +```ts +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](#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](#cryptoparam14) | 否 | 指定用户自定义的加密参数。
当此参数不填时,使用默认的加密参数,见[CryptoParam](#cryptoparam14)各参数默认值。
此配置只有在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](#encryptionalgo14) | 否 | 指定数据库加解密使用的加密算法。如不指定,默认值为 AES_256_GCM。 | +| hmacAlgo | [HmacAlgo](#hmacalgo14) | 否 | 指定数据库加解密使用的HMAC算法。如不指定,默认值为SHA256。 | +| kdfAlgo | [KdfAlgo](#kdfalgo14) | 否 | 指定数据库加解密使用的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](#assetstatus10) | 否 | 资产的状态,默认值为ASSET_NORMAL。 | + +## Assets10+ + +表示[Asset](#asset10)类型的数组。 + +| 类型 | 说明 | +| ------- | -------------------- | +| [Asset](#asset10)[] | 表示Asset类型的数组。 | + +## ValueType + +用于表示允许的数据字段类型。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 类型 | 说明 | +| ------- | -------------------- | +| null10+ | 表示值类型为空。 | +| number | 表示值类型为数字。 | +| string | 表示值类型为字符。 | +| boolean | 表示值类型为布尔值。 | +| Uint8Array10+ | 表示值类型为Uint8类型的数组。 | +| Asset10+ | 表示值类型为附件[Asset](#asset10)。 | +| Assets10+ | 表示值类型为附件数组[Assets](#assets10)。 | + +## ValuesBucket + +用于存储键值对的类型。该类型不是多线程安全的,如果应用中存在多线程同时操作该类派生出的实例,注意加锁保护。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 键类型 | 值类型 | +| ------ | ----------------------- | +| string | [ValueType](#valuetype) | + +## SqlExecutionInfo20+ + +描述数据库执行的SQL语句的统计信息。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 类型 | 只读 | 可选 |说明 | +| -------- | ------------------------------------------------- | ---- | ---- | -------------------------------------------------------- | +| sql12+ | Array<string> | 是 | 否 | 表示执行的SQL语句的数组。当[batchInsert](#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](#transactiontype14) | 否 | 事务类型。默认为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 | 是 | 数据库表名。 | + +**示例:** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +``` + +### equalTo + +equalTo(field: string, value: ValueType): RdbPredicates + +配置谓词以匹配数据字段为ValueType且值等于指定值的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------- | ---- | ---------------------- | +| field | string | 是 | 数据库表中的列名。 | +| value | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notEqualTo("NAME", "lisi"); +``` + + +### beginWrap + +beginWrap(): RdbPredicates + + +向谓词添加左括号。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回带有左括号的Rdb谓词。 | + +**示例:** + +```ts +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](#rdbpredicates) | 返回带有右括号的Rdb谓词。 | + +**示例:** + +```ts +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](#rdbpredicates) | 返回带有或条件的Rdb谓词。 | + +**示例:** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") +``` + +### and + +and(): RdbPredicates + +向谓词添加和条件。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回带有和条件的Rdb谓词。 | + +**示例:** + +```ts +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](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.endsWith("NAME", "se"); +``` + +### isNull + +isNull(field: string): RdbPredicates + +配置谓词以匹配值为null的字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例**: + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.isNull("NAME"); +``` + +### isNotNull + +isNotNull(field: string): RdbPredicates + +配置谓词以匹配值不为null的指定字段。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#valuetype) | 是 | 指示与谓词匹配的最小值。 | +| high | [ValueType](#valuetype) | 是 | 指示要与谓词匹配的最大值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#valuetype) | 是 | 指示要与谓词匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.lessThanOrEqualTo("AGE", 20); +``` + +### orderByAsc + +orderByAsc(field: string): RdbPredicates + +配置谓词以匹配其值按升序排序的列。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.orderByAsc("NAME"); +``` + +### orderByDesc + +orderByDesc(field: string): RdbPredicates + +配置谓词以匹配其值按降序排序的列。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ------------------ | +| field | string | 是 | 数据库表中的列名。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.orderByDesc("AGE"); +``` + +### distinct + +distinct(): RdbPredicates + +配置谓词以过滤重复记录并仅保留其中一个。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ------------------------------ | +| [RdbPredicates](#rdbpredicates) | 返回可用于过滤重复记录的谓词。 | + +**示例:** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.equalTo("NAME", "Rose").distinct(); +``` + +### limitAs + +limitAs(value: number): RdbPredicates + +设置最大数据记录数的谓词。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------- | +| value | number | 是 | 最大数据记录数。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------ | +| [RdbPredicates](#rdbpredicates) | 返回可用于设置最大数据记录数的谓词。 | + +**示例:** + +```ts +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](#rdbpredicates) | 返回具有指定返回结果起始位置的谓词。 | + +**示例:** + +```ts +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](#rdbpredicates) | 返回分组查询列的谓词。 | + +**示例:** + +```ts +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.groupBy(["AGE", "NAME"]); +``` + +### indexedBy + +indexedBy(field: string): RdbPredicates + +配置RdbPredicates以指定索引列。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ----------- | +| field | string | 是 | 索引列的名称。 | + +**返回值**: + + +| 类型 | 说明 | +| ------------------------------------ | ------------------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回具有指定索引列的RdbPredicates。 | + +**示例:** + +```ts +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)> | 是 | 以ValueType型数组形式指定的要匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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)> | 是 | 以ValueType数组形式指定的要匹配的值。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------ | -------------------------- | +| [RdbPredicates](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**示例:** + +```ts +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](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 + +| **错误码ID** | **错误信息** | +| --------- |----------------------------------------------------------------------------------------------------------------| +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | + +**示例:** + +```ts +// 匹配数据表的"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](#rdbpredicates) | 返回与指定字段匹配的谓词。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 + +| **错误码ID** | **错误信息** | +| --------- |----------------------------------------------------------------------------------------------------------------| +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | + +**示例:** + +```ts +// 匹配数据表的"NAME"列中不等于"os"的字段,如列表中的"Rose" +let predicates = new relationalStore.RdbPredicates("EMPLOYEE"); +predicates.notLike("NAME", "os"); +``` + +## RdbStore + +提供管理关系数据库(RDB)方法的接口。 + +在使用以下相关接口前,请使用[executeSql](#executesql)接口初始化数据库表结构和相关数据。 + +### 属性10+ + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +| 名称 | 类型 | 必填 | 说明 | +| ------------ | ----------- | ---- | --------------------------------- | +| version10+ | number | 是 | 设置和获取数据库版本,值为大于0的正整数。 | + +**示例:** + +```ts +// 设置数据库版本 +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](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回行ID;否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回行ID;否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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}`); + }) +} +``` + +### insertSync20+ + +insertSync(table: string, values: sendableRelationalStore.ValuesBucket, conflict?: ConflictResolution):number + +传入Sendable数据,向目标表中插入一行数据。由于共享内存大小限制为2Mb,因此单条数据的大小需小于2Mb,否则会查询失败。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------------------------------------------------------------- | ---- | ------------------------------------------------------------------------------- | +| table | string | 是 | 指定的目标表名。 | +| values | [sendableRelationalStore.ValuesBucket](./js-apis-data-sendableRelationalStore.md#valuesbucket) | 是 | 表示要插入到表中的可跨线程传递数据。 | +| conflict | [ConflictResolution](#conflictresolution10) | 否 | 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。 | + +**返回值**: + +| 类型 | 说明 | +| ------ | ------------------------------------ | +| number | 如果操作成功,返回行ID;否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | +| 14800015 | The database does not respond. | +| 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. | +| 14800047 | The WAL file size exceeds the default limit. | + +**示例:** + +```ts +import { sendableRelationalStore } from '@kit.ArkData'; + +const valuesBucket: relationalStore.ValuesBucket = { + "NAME": 'hangman', + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3]) +}; +const sendableValuesBucket = sendableRelationalStore.toSendableValuesBucket(valuesBucket); + +if (store != undefined) { + try { + let rowId: number = (store as relationalStore.RdbStore).insertSync("EMPLOYEE", sendableValuesBucket, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); + console.info(`Insert is successful, rowId = ${rowId}`); + } catch (error) { + console.error(`Insert is failed, code is ${error.code},message is ${error.message}`); + } +} +``` + +### batchInsert + +batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void + +向目标表中插入一组数据,使用callback异步回调。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| values | Array<[ValuesBucket](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。如果操作成功,返回插入的数据个数,否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#begintransaction)的区别在于:createTransaction接口会返回一个事务对象,不同事务对象之间是隔离的。使用事务对象进行插入、删除或更新数据等操作,无法被注册数据变更通知[on('dataChange')](#ondatachange)监听到。 + +一个store最多支持同时存在四个事务对象,超过后会返回14800015错误码,此时需要检查是否持有事务对象时间过长或并发事务过多,若确认无法通过上述优化解决问题,建议等待现有事务释放后,再尝试新建事务对象。 + +优先使用createTransaction,不再推荐使用beginTransaction。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ----------------------------- | ---- | ------------------------------------------------------------ | +| options | [TransactionOptions](#transactionoptions14) | 否 | 表示事务对象的配置信息。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<[Transaction](#transaction14)> | Promise对象,返回事务对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 | +| callback | AsyncCallback<number> | 是 | 指定的callback回调方法。返回受影响的行数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------- | +| Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决方式。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------- | +| Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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) | 是 | RdbPredicates的实例对象指定的删除条件。 | +| callback | AsyncCallback<number> | 是 | 指定callback回调函数。返回受影响的行数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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) | 是 | RdbPredicates的实例对象指定的删除条件。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ------------------------------- | +| Promise<number> | Promise对象。返回受影响的行数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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) | 是 | RdbPredicates的实例对象指定的查询条件。 | +| callback | AsyncCallback<[ResultSet](#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**示例:** + +```ts +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) | 是 | RdbPredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 是 | 表示要查询的列。如果值为空,则查询应用于所有列。 | +| callback | AsyncCallback<[ResultSet](#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**示例:** + +```ts +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) | 是 | RdbPredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise对象。如果操作成功,则返回ResultSet对象。 | + +**示例:** + +```ts +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](#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#valuetype)> | 是 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数需为空数组。 | +| callback | AsyncCallback<[ResultSet](#resultset)> | 是 | 指定callback回调函数。如果操作成功,则返回ResultSet对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#valuetype)> | 否 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise对象。如果操作成功,则返回ResultSet对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**示例:** + +```ts +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回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#valuetype)> | 是 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数需为空数组。 | +| callback | AsyncCallback<void> | 是 | 指定callback回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#valuetype)> | 否 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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 + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | -------------------------------------------- | +| 14800047 | The WAL file size exceeds the default limit. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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 + +**示例:** + +```ts +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 + +**示例:** + +```ts +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回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**示例:** + +```ts +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对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**示例:** + +```ts +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回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**示例:** + +```ts +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对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ---------------------------- | +| 14800000 | Inner error. | + +**示例:** + +```ts +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](#sqlexecutioninfo12)> | 是 | 回调函数。用于返回数据库中SQL执行时间的统计信息。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。 + +| **错误码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. | + +**示例:** + +```ts +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对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ----------------------------------------------- | +| 401 | Parameter error. The store must not be nullptr. | +| 14800000 | Inner error. | + +**示例:** + +```ts +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对象。 + +```ts +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 | 返回指定列的索引。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + +```ts +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 | 返回指定列的名称。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + +```ts +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。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goTo(1); +} +``` + +### goToRow + +goToRow(position: number): boolean + +转到结果集的指定行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------ | +| position | number | 是 | 表示要移动到的指定位置。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goToRow(5); +} +``` + +### goToFirstRow + +goToFirstRow(): boolean + + +转到结果集的第一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goToFirstRow(); +} +``` + +### goToLastRow + +goToLastRow(): boolean + +转到结果集的最后一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goToLastRow(); +} +``` + +### goToNextRow + +goToNextRow(): boolean + +转到结果集的下一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goToNextRow(); +} +``` + +### goToPreviousRow + +goToPreviousRow(): boolean + +转到结果集的上一行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ------- | --------------------------------------------- | +| boolean | 如果成功移动结果集,则为true;否则返回false。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +**示例:** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).goToPreviousRow(); +} +``` + +### getBlob + +getBlob(columnIndex: number): Uint8Array + +以字节数组的形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | ---- | ----------------------- | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ---------- | -------------------------------- | +| Uint8Array | 以字节数组的形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + +```ts +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](#valuetype) | 表示允许的数据字段类型。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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 | 以字符串形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + +```ts +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](#getdouble)。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + +```ts +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形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + +```ts +if(resultSet != undefined) { +const salary = (resultSet as relationalStore.ResultSet).getDouble((resultSet as relationalStore.ResultSet).getColumnIndex("SALARY")); +} +``` + +### getAsset10+ + +getAsset(columnIndex: number): Asset + +以[Asset](#asset10)形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | --- | ------------ | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| --------------- | -------------------------- | +| [Asset](#asset10) | 以Asset形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| --------- | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + +```ts +if(resultSet != undefined) { +const doc = (resultSet as relationalStore.ResultSet).getAsset((resultSet as relationalStore.ResultSet).getColumnIndex("DOC")); +} +``` + +### getAssets10+ + +getAssets(columnIndex: number): Assets + +以[Assets](#assets10)形式获取当前行中指定列的值。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----------- | ------ | --- | ------------ | +| columnIndex | number | 是 | 指定的列索引,从0开始。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ---------------------------- | +| [Assets](#assets10)| 以Assets形式返回指定列的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + +```ts +if(resultSet != undefined) { +const docs = (resultSet as relationalStore.ResultSet).getAssets((resultSet as relationalStore.ResultSet).getColumnIndex("DOCS")); +} +``` + +### getRow20+ + +getRow(): ValuesBucket + +获取当前行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**返回值:** + +| 类型 | 说明 | +| ---------------- | ---------------------------- | +| [ValuesBucket](#valuesbucket) | 返回指定行的值。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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。 | + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800013 | The column value is null or the column type is incompatible. | + +**示例:** + +```ts +if(resultSet != undefined) { +const isColumnNull = (resultSet as relationalStore.ResultSet).isColumnNull((resultSet as relationalStore.ResultSet).getColumnIndex("CODES")); +} +``` + +### close + +close(): void + +关闭结果集。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + +```ts +if(resultSet != undefined) { +(resultSet as relationalStore.ResultSet).close(); +} +``` + +**错误码:** + +以下错误码的详细介绍请参见[关系型数据库错误码](../errorcodes/errorcode-data-rdb.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------------------------ | +| 14800012 | The result set is empty or the specified location is invalid. | + +## Transaction20+ + +提供以事务方式管理数据库的方法。事务对象是通过[createTransaction](#createtransaction14)接口创建的,不同事务对象之间的操作是隔离的,不同类型事务的区别见[TransactionType](#transactiontype14) 。 + +当前关系型数据库同一时刻仅支持一个写事务,所以如果当前[RdbStore](#rdbstore)存在写事务未释放,创建IMMEDIATE或EXCLUSIVE事务会返回14800024错误码。如果是创建的DEFERRED事务,则可能在首次使用DEFERRED事务调用写操作时返回14800024错误码。通过IMMEDIATE或EXCLUSIVE创建写事务或者DEFERRED事务升级到写事务之后,[RdbStore](#rdbstore)的写操作也会返回14800024错误码。 + +当事务并发量较高且写事务持续时间较长时,返回14800024错误码的次数可能会变多,开发者可以通过减少事务占用时长减少14800024出现的次数,也可以通过重试的方式处理14800024错误码。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**示例:** + +```ts +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对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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](#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| conflict | [ConflictResolution](#conflictresolution10) | 否 | 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回行ID;否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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}`); + }); +} +``` + +### insertSync20+ + +insertSync(table: string, values: ValuesBucket | sendableRelationalStore.ValuesBucket, conflict?: ConflictResolution): number + +向目标表中插入一行数据。由于共享内存大小限制为2Mb,因此单条数据的大小需小于2Mb,否则会查询失败。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| table | string | 是 | 指定的目标表名。 | +| values | [ValuesBucket](#valuesbucket) \| [sendableRelationalStore.ValuesBucket](./js-apis-data-sendableRelationalStore.md#valuesbucket) | 是 | 表示要插入到表中的数据行。 | +| conflict | [ConflictResolution](#conflictresolution10) | 否 | 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。 | + +**返回值**: + +| 类型 | 说明 | +| ------ | ------------------------------------ | +| number | 如果操作成功,返回行ID;否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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) => { + try { + let rowId: number = (transaction as relationalStore.Transaction).insertSync("EMPLOYEE", valueBucket1, relationalStore.ConflictResolution.ON_CONFLICT_REPLACE); + transaction.commit(); + console.info(`Insert is successful, rowId = ${rowId}`); + } catch (e) { + 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](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。| + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | + +**返回值**: + +| 类型 | 说明 | +| ------ | ---------------------------------------------- | +| number | 如果操作成功,返回插入的数据个数,否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。| +| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决模式。如果是ON_CONFLICT_ROLLBACK模式,当发生冲突时会回滚整个事务。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------------------------- | +| Promise<number> | Promise对象。如果操作成功,返回插入的数据个数,否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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](#valuesbucket)> | 是 | 表示要插入到表中的一组数据。 | +| conflict | [ConflictResolution](#conflictresolution10) | 是 | 指定冲突解决模式。如果是ON_CONFLICT_ROLLBACK模式,当发生冲突时会回滚整个事务。 | + +**返回值**: + +| 类型 | 说明 | +| ------ | ---------------------------------------------- | +| number | 如果操作成功,返回插入的数据个数,否则返回-1。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| conflict | [ConflictResolution](#conflictresolution10) | 否 | 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ----------------------------------------- | +| Promise<number> | 指定的Promise回调方法。返回受影响的行数。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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](#valuesbucket) | 是 | values指示数据库中要更新的数据行。键值对与数据库表的列名相关联。 | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的更新条件。 | +| conflict | [ConflictResolution](#conflictresolution10) | 否 | 指定冲突解决模式。默认值是relationalStore.ConflictResolution.ON_CONFLICT_NONE。 | + +**返回值**: + +| 类型 | 说明 | +| ------ | ------------------ | +| number | 返回受影响的行数。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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) | 是 | RdbPredicates的实例对象指定的删除条件。 | + +**返回值**: + +| 类型 | 说明 | +| --------------------- | ------------------------------- | +| Promise<number> | Promise对象。返回受影响的行数。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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) | 是 | RdbPredicates的实例对象指定的删除条件。 | + +**返回值**: + +| 类型 | 说明 | +| ------ | ------------------ | +| number | 返回受影响的行数。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +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) | 是 | RdbPredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。 + +| **错误码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](#resultset)> | Promise对象。如果操作成功,则返回ResultSet对象。 | + +**示例:** + +```ts +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](../apis-arkts/js-apis-taskpool.md)线程中执行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| predicates | [RdbPredicates](#rdbpredicates) | 是 | RdbPredicates的实例对象指定的查询条件。 | +| columns | Array<string> | 否 | 表示要查询的列。如果值为空,则查询应用于所有列。默认值为空。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。 + +| **错误码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) | 如果操作成功,则返回ResultSet对象。 | + +**示例:** + +```ts +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](#valuetype)> | 否 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------------------------------------------- | -------------------------------------------------- | +| Promise<[ResultSet](#resultset)> | Promise对象。如果操作成功,则返回ResultSet对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。 + +| **错误码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. | + +**示例:** + +```ts +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](../apis-arkts/js-apis-taskpool.md)线程中执行。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | 是 | 指定要执行的SQL语句。 | +| args | Array<[ValueType](#valuetype)> | 否 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。默认值为空。 | + +**返回值**: + +| 类型 | 说明 | +| ----------------------- | ----------------------------------- | +| [ResultSet](#resultset) | 如果操作成功,则返回ResultSet对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。 + +| **错误码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. | + +**示例:** + +```ts +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的结果决定。 + +此接口不支持执行查询、附加数据库和事务操作,查询可以使用[querySql](#querysql14)、[query](#query14)接口代替、附加数据库可以使用[attach](#attach12)接口代替。 + +不支持分号分隔的多条语句。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | 是 | 指定要执行的SQL语句。 | +| args | Array<[ValueType](#valuetype)> | 否 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。当sql参数语句完整时,该参数不填。 | + +**返回值**: + +| 类型 | 说明 | +| ------------------- | ------------------------- | +| Promise<[ValueType](#valuetype)> | Promise对象,返回sql执行后的结果。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +// 删除表中所有数据 +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的结果决定。 + +此接口不支持执行查询、附加数据库和事务操作,查询可以使用[querySql](#querysql14)、[query](#query14)接口代替、附加数据库可以使用[attach](#attach12)接口代替。 + +不支持分号分隔的多条语句。 + +**系统能力:** SystemCapability.DistributedDataManager.RelationalStore.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------------ | ---- | ------------------------------------------------------------ | +| sql | string | 是 | 指定要执行的SQL语句。 | +| args | Array<[ValueType](#valuetype)> | 否 | SQL语句中参数的值。该值与sql参数语句中的占位符相对应。该参数不填,或者填null或undefined,都认为是sql参数语句完整。默认值为空。 | + +**返回值**: + +| 类型 | 说明 | +| ----------------------- | ------------------- | +| [ValueType](#valuetype) | 返回sql执行后的结果。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[关系型数据库错误码](errorcode-data-rdb.md)。其中,14800011错误码处理可参考[数据库备份与恢复](../../database/data-backup-and-restore.md)。 + +| **错误码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. | + +**示例:** + +```ts +// 删除表中所有数据 +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}`); + }); +} +``` diff --git a/arkuix_zh/js-apis-data-uniformTypeDescriptor.md b/arkuix_zh/js-apis-data-uniformTypeDescriptor.md new file mode 100644 index 0000000000000000000000000000000000000000..6b82089be05afb88179334653605b57baf1947ea --- /dev/null +++ b/arkuix_zh/js-apis-data-uniformTypeDescriptor.md @@ -0,0 +1,516 @@ +# @ohos.data.uniformTypeDescriptor (标准化数据定义与描述) + +本模块对标准化数据类型进行了抽象定义与描述。 + +> **说明:** +> +> 本模块首批接口从API version 10开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```js +import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor'; +``` + +## UniformDataType + +标准化数据类型的枚举定义。标准化数据类型之间存在归属关系,例如JPEG图片类型归属于IMAGE类型。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 值 | 说明 | Android平台 | iOS平台 | +|----------------------------|------------------------------|------------------------------------|------------------------------------|------------------------------------| +| TEXT | 'general.text' | 所有文本的基类型,归属类型为OBJECT。 | 支持 | 支持 | +| PLAIN_TEXT | 'general.plain-text' | 未指定编码的文本类型,没有标识符,归属类型为TEXT。 | 支持 | 支持 | +| HTML | 'general.html' | HTML文本类型,归属类型为TEXT。 | 支持 | 支持 | +| HYPERLINK | 'general.hyperlink' | 超链接类型,归属类型为TEXT。 | 支持 | 支持 | +| IMAGE | 'general.image' | 所有图片的基类型,归属类型为MEDIA。 | 支持 | 支持 | +| VIDEO | 'general.video' | 所有视频的基类型,归属类型为MEDIA。 | 支持 | 支持 | +| AUDIO | 'general.audio' | 所有音频的基类型,归属类型为MEDIA。 | 支持 | 支持 | +| FILE | 'general.file' | 所有文件的基类型,归属类型为ENTITY。 | 支持 | 支持 | +| FOLDER | 'general.folder' | 所有文件夹的基类型,归属类型为DIRECTORY。 | 支持 | 支持 | +| OPENHARMONY_PIXEL_MAP | 'openharmony.pixel-map' | 系统定义的像素图类型,归属类型为IMAGE。 | 支持 | 支持 | + +## TypeDescriptor20+ + +标准化数据类型的描述类,它包含了一些属性和方法用于描述标准化数据类型自身以及和其他标准化数据类型之间的归属与层级关系。 + +### 属性 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +| 名称 | 类型 | 只读 | 可选 | 说明 | +| ------- | ----------------------- | ---- | ---- |----------------------------------------------------------| +| typeId11+ | string | 是 | 否 | 标准化数据类型的ID(即[UTD列表](#uniformdatatype)中对应的枚举值),也可以是自定义UTD。 | +| belongingToTypes11+ | Array\ | 是 | 否 | 标准化数据类型所归属的类型typeId列表。 | +| description11+ | string | 是 | 否 | 标准化数据类型的简要说明。 | +| referenceURL11+ | string | 是 | 否 | 标准化数据类型的参考链接URL,用于描述类型的详细信息。 | +| iconFile11+ | string | 是 | 否 | 标准化数据类型的默认图标文件路径,可能为空字符串(即没有默认图标),应用可以自行决定是否使用该默认图标。 | +| filenameExtensions12+ | Array\ | 是 | 否 | 标准化数据类型所关联的文件名后缀列表。 | +| mimeTypes12+ | Array\ | 是 | 否 | 标准化数据类型所关联的多用途互联网邮件扩展类型列表。 | + +### belongsTo11+ + +belongsTo(type: string): boolean + +判断当前标准化数据类型是否归属于指定的标准化数据类型。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------------- | +| type | string | 是 |所指定的标准化数据类型(即[UniformDataType](#uniformdatatype)中对应的枚举值)。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| boolean | 返回true表示当前的标准化数据类型归属于所指定的标准化数据类型,包括所指定类型与当前类型相同的情况;返回false则表示无归属关系。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | + +**示例:** + +```ts +import { uniformTypeDescriptor } from '@kit.ArkData'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try{ + let typeObj : uniformTypeDescriptor.TypeDescriptor = uniformTypeDescriptor.getTypeDescriptor('general.type-script'); + let ret = typeObj.belongsTo('general.source-code'); + if(ret) { + console.info('type general.type-script belongs to type general.source-code'); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`belongsTo throws an exception. code is ${error.code}, message is ${error.message} `); +} +``` + +### isLowerLevelType20+ + +isLowerLevelType(type: string): boolean + +判断当前标准化数据类型是否是指定标准化数据类型的低层级类型。例如TYPE_SCRIPT为SOURCE_CODE的低层级类型,TYPE_SCRIPT和SOURCE_CODE为TEXT的低层级类型。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------------- | +| type | string | 是 |所指定的标准化数据类型(即[UniformDataType](#uniformdatatype)中对应的枚举值)。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| boolean | 返回true表示当前的标准化数据类型是所指定标准化数据类型的低层级类型,否则返回false。| + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | + +**示例:** + +```ts +import { uniformTypeDescriptor } from '@kit.ArkData'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try{ + let typeObj : uniformTypeDescriptor.TypeDescriptor = uniformTypeDescriptor.getTypeDescriptor('general.type-script'); + let ret = typeObj.isLowerLevelType('general.source-code'); + if(ret) { + console.info('type general.type-script is lower level type of type general.source-code'); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`isLowerLevelType throws an exception. code is ${error.code}, message is ${error.message} `); +} +``` + +### isHigherLevelType20+ + +isHigherLevelType(type: string): boolean + +判断当前标准化数据类型是否是指定标准化数据类型的高层级类型。例如SOURCE_CODE为TYPE_SCRIPT的高层级类型,TEXT为SOURCE_CODE和TYPE_SCRIPT的高层级类型。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------------- | +| type | string | 是 |所指定的标准化数据类型(即[UniformDataType](#uniformdatatype)中对应的枚举值)。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| boolean | 返回true表示当前的标准化数据类型是所指定标准化数据类型的高层级类型,否则返回false。| + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | + +**示例:** + +```ts +import { uniformTypeDescriptor } from '@kit.ArkData'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try{ + let typeObj : uniformTypeDescriptor.TypeDescriptor = uniformTypeDescriptor.getTypeDescriptor('general.source-code'); + let ret = typeObj.isHigherLevelType('general.type-script'); + if(ret) { + console.info('type general.source-code is higher level type of type general.type-script'); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`isHigherLevelType throws an exception. code is ${error.code}, message is ${error.message} `); +} +``` + +### equals20+ + +equals(typeDescriptor: TypeDescriptor): boolean + +判断指定的标准化数据类型描述类对象的类型ID和当前标准化数据类型描述类对象的类型ID是否相同,即[TypeDescriptor](#typedescriptor11)对象的typeId。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------------- | +| typeDescriptor | [TypeDescriptor](#typedescriptor11) | 是 |待比较的标准化数据类型描述类对象。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| boolean | 返回true表示所比较的标准化数据类型相同;返回false则表示不同。 | + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | + +**示例:** + +```ts +import { uniformTypeDescriptor } from '@kit.ArkData'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try{ + let typeA : uniformTypeDescriptor.TypeDescriptor = uniformTypeDescriptor.getTypeDescriptor('general.type-script'); + let typeB : uniformTypeDescriptor.TypeDescriptor = uniformTypeDescriptor.getTypeDescriptor('general.python-script'); + if(!typeA.equals(typeB)) { + console.info('typeA is not equal to typeB'); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`throws an exception. code is ${error.code}, message is ${error.message} `); +} +``` + +## uniformTypeDescriptor.getTypeDescriptor20+ + +getTypeDescriptor(typeId: string): TypeDescriptor + +按给定的标准化数据类型ID查询并返回对应的标准化数据类型描述类对象。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------------- | +| typeId | string | 是 |[标准化数据类型ID](../../database/uniform-data-type-list.md#基础类型)。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| [TypeDescriptor](#typedescriptor11) | 返回标准化数据类型描述类对象,如果要查询的标准化数据类型不存在则返回null。| + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | + +**示例:** + +```ts +import { uniformTypeDescriptor } from '@kit.ArkData'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + let typeObj : uniformTypeDescriptor.TypeDescriptor = uniformTypeDescriptor.getTypeDescriptor('com.adobe.photoshop-image'); + if (typeObj) { + let typeId = typeObj.typeId; + let belongingToTypes = typeObj.belongingToTypes; + let description = typeObj.description; + let referenceURL = typeObj.referenceURL; + let iconFile = typeObj.iconFile; + let filenameExtensions = typeObj.filenameExtensions; + let mimeTypes = typeObj.mimeTypes; + console.info(`typeId: ${typeId}, belongingToTypes: ${belongingToTypes}, description: ${description}, referenceURL: ${referenceURL}, iconFile: ${iconFile}, filenameExtensions: ${filenameExtensions}, mimeTypes: ${mimeTypes}`); + } else { + console.info('type com.adobe.photoshop-image does not exist'); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`getTypeDescriptor throws an exception. code is ${error.code}, message is ${error.message} `); +} +``` + +## uniformTypeDescriptor.getUniformDataTypeByFilenameExtension20+ + +getUniformDataTypeByFilenameExtension(filenameExtension: string, belongsTo?: string): string + +根据给定的文件后缀名和所归属的标准化数据类型查询标准化数据类型ID,若有多个符合条件的标准化数据类型ID,则返回第一个。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------------- | +| filenameExtension | string | 是 |文件后缀名称。 | +| belongsTo | string | 否 |要查询的标准化数据类型所归属类型ID,无默认值,若不传入此参数则只按照文件后缀名称查询[标准化数据类型ID](../../database/uniform-data-type-list.md#基础类型)。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| string | 返回与给定文件后缀名以及归属类型ID(如果设置了belongsTo参数)匹配的标准化数据类型ID,如果要查询的标准化数据类型不存在则返回根据入参按指定规则生成的动态类型。| + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | + +**示例:** + +```ts +import { uniformTypeDescriptor } from '@kit.ArkData'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + let typeId = uniformTypeDescriptor.getUniformDataTypeByFilenameExtension('.ts', 'general.source-code'); + if(typeId) { + console.info('typeId is general.type-script'); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`getUniformDataTypeByFilenameExtension throws an exception. code is ${error.code}, message is ${error.message} `); +} + +// 根据“.myts”,“general.plain-text”查不到预置数据类型则按返回根据入参信息生成的动态类型。 +try { + let typeId = uniformTypeDescriptor.getUniformDataTypeByFilenameExtension('.myts', 'general.plain-text'); + if(typeId) { + console.info('typeId is flex.************'); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`getUniformDataTypeByFilenameExtension throws an exception. code is ${error.code}, message is ${error.message} `); +} +``` + +## uniformTypeDescriptor.getUniformDataTypeByMIMEType20+ + +getUniformDataTypeByMIMEType(mimeType: string, belongsTo?: string): string + +根据给定的MIME类型和所归属的标准化数据类型查询标准化数据类型ID,若有多个符合条件的标准化数据类型ID,则返回第一个。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------------- | +| mimeType | string | 是 |MIME类型名称。 | +| belongsTo | string | 否 |要查询的标准化数据类型所归属类型ID。无默认值,若不传入此参数则只按照MIME类型名称查询[标准化数据类型ID](../../database/uniform-data-type-list.md#基础类型)。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| string | 返回与MIME类型名称以及归属类型ID(如果设置了belongsTo参数)匹配的标准化数据类型ID,如果要查询的标准化数据类型不存在则返回根据入参按指定规则生成的动态类型。| + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | + +**示例:** + +```ts +import { uniformTypeDescriptor } from '@kit.ArkData'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + let typeId = uniformTypeDescriptor.getUniformDataTypeByMIMEType('image/jpeg', 'general.image'); + if(typeId) { + console.info('typeId is general.jpeg'); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`getUniformDataTypeByMIMEType throws an exception. code is ${error.code}, message is ${error.message} `); +} + +// 根据“image/myimage”, “general.image”查不到预置数据类型则按返回根据入参信息生成的动态类型。 +try { + let typeId = uniformTypeDescriptor.getUniformDataTypeByMIMEType('image/myimage', 'general.image'); + if(typeId) { + console.info('typeId is flex.************'); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`getUniformDataTypeByMIMEType throws an exception. code is ${error.code}, message is ${error.message} `); +} +``` + +## uniformTypeDescriptor.getUniformDataTypesByFilenameExtension20+ + +getUniformDataTypesByFilenameExtension(filenameExtension: string, belongsTo?: string): Array\ + +根据给定的文件后缀名和所归属的标准化数据类型查询标准化数据类型ID列表。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------------- | +| filenameExtension | string | 是 |文件后缀名称。 | +| belongsTo | string | 否 |要查询的标准化数据类型所归属类型ID,无默认值,若不传入此参数则只按照文件后缀名称查询[标准化数据类型ID](../../database/uniform-data-type-list.md#基础类型)。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| Array\ | 返回与给定文件后缀名以及归属类型ID(如果设置了belongsTo参数)匹配的标准化数据类型ID列表,如果要查询的标准化数据类型不存在则返回根据入参按指定规则生成的动态类型列表。| + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | + +**示例:** + +```ts +import { uniformTypeDescriptor } from '@kit.ArkData'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + let typeIds = uniformTypeDescriptor.getUniformDataTypesByFilenameExtension('.ts', 'general.source-code'); + for (let typeId of typeIds) { + console.info(`typeId is ${typeId}`); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`getUniformDataTypesByFilenameExtension throws an exception. code is ${error.code}, message is ${error.message} `); +} + +// 根据“.myts”,“general.plain-text”查不到预置数据类型则按返回根据入参信息生成的动态类型列表。 +try { + let flexTypeIds = uniformTypeDescriptor.getUniformDataTypesByFilenameExtension('.myts', 'general.plain-text'); + for (let flexTypeId of flexTypeIds) { + console.info(`typeId is flex type, flex typeId is ${flexTypeId}`); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`getUniformDataTypesByFilenameExtension throws an exception. code is ${error.code}, message is ${error.message} `); +} +``` + +## uniformTypeDescriptor.getUniformDataTypesByMIMEType20+ + +getUniformDataTypesByMIMEType(mimeType: string, belongsTo?: string): Array\ + +根据给定的MIME类型和所归属的标准化数据类型查询标准化数据类型ID列表。 + +**系统能力:** SystemCapability.DistributedDataManager.UDMF.Core + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------------- | +| mimeType | string | 是 |MIME类型名称。 | +| belongsTo | string | 否 |要查询的标准化数据类型所归属类型ID。无默认值,若不传入此参数则只按照MIME类型名称查询[标准化数据类型ID](../../database/uniform-data-type-list.md#基础类型)。 | + +**返回值:** + +| 类型 | 说明 | +| ------- | ------------------------------------------------------------ | +| Array\ | 返回与MIME类型名称以及归属类型ID(如果设置了belongsTo参数)匹配的标准化数据类型ID列表,如果要查询的标准化数据类型不存在则返回根据入参按指定规则生成的动态类型列表。| + +**错误码:** + +以下错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。 + +| **错误码ID** | **错误信息** | +| ------------ | ------------------------------------------- | +| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameters types. | + +**示例:** + +```ts +import { uniformTypeDescriptor } from '@kit.ArkData'; +import { BusinessError } from '@kit.BasicServicesKit'; + +try { + let typeIds = uniformTypeDescriptor.getUniformDataTypesByMIMEType('text/plain', 'general.text'); + for (let typeId of typeIds) { + console.info(`typeId is ${typeId}`); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`getUniformDataTypesByMIMEType throws an exception. code is ${error.code}, message is ${error.message} `); +} + +// 根据“image/myimage”, “general.image”查不到预置数据类型则按返回根据入参信息生成的动态类型列表。 +try { + let flexTypeIds = uniformTypeDescriptor.getUniformDataTypesByMIMEType('image/myimage', 'general.image'); + for (let flexTypeId of flexTypeIds) { + console.info(`typeId is flex type, flex typeId is ${flexTypeId}`); + } +} catch(e) { + let error: BusinessError = e as BusinessError; + console.error(`getUniformDataTypesByMIMEType throws an exception. code is ${error.code}, message is ${error.message} `); +} +``` diff --git a/arkuix_zh/js-apis-request.md b/arkuix_zh/js-apis-request.md new file mode 100644 index 0000000000000000000000000000000000000000..97d4616967b5f22078478296f38a10de9c732830 --- /dev/null +++ b/arkuix_zh/js-apis-request.md @@ -0,0 +1,3483 @@ +# @ohos.request (Upload and Download) + +The **request** module provides applications with basic upload, download, and background transmission agent capabilities. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + + +```js +import request from '@ohos.request'; +``` + +## Constants + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +### Network Types +You can set **networkType** in [DownloadConfig](#downloadconfig) to specify the network type for the download service. + +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| NETWORK_MOBILE | number | 0x00000001 | Whether download is allowed on a mobile network.| +| NETWORK_WIFI | number | 0x00010000 | Whether download is allowed on a WLAN.| + +### Download Error Codes +The table below lists the values of **err** in the callback of [on('fail')7+](#onfail7) and the values of **failedReason** returned by [getTaskInfo9+](#gettaskinfo9). + +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| ERROR_CANNOT_RESUME7+ | number | 0 | Failure to resume the download due to network errors.| +| ERROR_DEVICE_NOT_FOUND7+ | number | 1 | Failure to find a storage device such as a memory card.| +| ERROR_FILE_ALREADY_EXISTS7+ | number | 2 | Failure to download the file because it already exists.| +| ERROR_FILE_ERROR7+ | number | 3 | File operation failure.| +| ERROR_HTTP_DATA_ERROR7+ | number | 4 | HTTP transmission failure.| +| ERROR_INSUFFICIENT_SPACE7+ | number | 5 | Insufficient storage space.| +| ERROR_TOO_MANY_REDIRECTS7+ | number | 6 | Error caused by too many network redirections.| +| ERROR_UNHANDLED_HTTP_CODE7+ | number | 7 | Unidentified HTTP code.| +| ERROR_UNKNOWN7+ | number | 8 | Unknown error.| +| ERROR_OFFLINE9+ | number | 9 | No network connection.| +| ERROR_UNSUPPORTED_NETWORK_TYPE9+ | number | 10 | Network type mismatch.| + + +### Causes of Download Pause +The table below lists the values of **pausedReason** returned by [getTaskInfo9+](#gettaskinfo9). + +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| PAUSED_QUEUED_FOR_WIFI7+ | number | 0 | Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a mobile network session.| +| PAUSED_WAITING_FOR_NETWORK7+ | number | 1 | Download paused due to a network connection problem, for example, network disconnection.| +| PAUSED_WAITING_TO_RETRY7+ | number | 2 | Download paused and then retried.| +| PAUSED_BY_USER9+ | number | 3 | The user paused the session.| +| PAUSED_UNKNOWN7+ | number | 4 | Download paused due to unknown reasons.| + +### Download Task Status Codes +The table below lists the values of **status** returned by [getTaskInfo9+](#gettaskinfo9). + +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| SESSION_SUCCESSFUL7+ | number | 0 | Successful download.| +| SESSION_RUNNING7+ | number | 1 | Download in progress.| +| SESSION_PENDING7+ | number | 2 | Download pending.| +| SESSION_PAUSED7+ | number | 3 | Download paused.| +| SESSION_FAILED7+ | number | 4 | Download failure without retry.| + + +## request.uploadFile9+ + +uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> + +Uploads files. This API uses a promise to return the result. You can use [on('complete'|'fail')9+](#oncomplete--fail9) to obtain the upload error information. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400002 | bad file path. | + +**Example** + + ```js + let uploadTask; + let uploadConfig = { + url: 'http://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], + }; + try { + request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => { + uploadTask = data; + }).catch((err) => { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } + ``` + + +## request.uploadFile9+ + +uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void + +Uploads files. This API uses an asynchronous callback to return the result. You can use [on('complete'|'fail')9+](#oncomplete--fail9) to obtain the upload error information. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400002 | bad file path. | + +**Example** + + ```js + let uploadTask; + let uploadConfig = { + url: 'http://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], + }; + try { + request.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => { + if (err) { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + return; + } + uploadTask = data; + }); + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } + ``` + +## UploadTask + +Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object through [request.uploadFile9+](#requestuploadfile9) in promise mode or [request.uploadFile9+](#requestuploadfile9-1) in callback mode. + + + +### on('progress') + +on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => void): void + +Subscribes to upload progress events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| +| callback | function | Yes| Callback for the upload progress event.| + + Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| uploadedSize | number | Yes| Size of the uploaded files, in bytes.| +| totalSize | number | Yes| Total size of the files to upload, in bytes.| + +**Example** + + ```js + let upProgressCallback = (uploadedSize, totalSize) => { + console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); + }; + uploadTask.on('progress', upProgressCallback); + ``` + + +### on('headerReceive')7+ + +on(type: 'headerReceive', callback: (header: object) => void): void + +Subscribes to HTTP header events for an upload task. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).| +| callback | function | Yes| Callback for the HTTP Response Header event.| + + Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| header | object | Yes| HTTP Response Header.| + +**Example** + + ```js + let headerCallback = (headers) => { + console.info("upOnHeader headers:" + JSON.stringify(headers)); + }; + uploadTask.on('headerReceive', headerCallback); + ``` + + +### on('complete' | 'fail')9+ + + on(type:'complete' | 'fail', callback: Callback<Array<TaskState>>): void; + +Subscribes to upload completion or failure events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| +| callback | Callback<Array<TaskState>> | Yes| Callback used to return the result.| + + Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| taskstates | Array<[TaskState](#taskstate9)> | Yes| Upload result.| + +**Example** + + ```js + let upCompleteCallback = (taskStates) => { + for (let i = 0; i < taskStates.length; i++ ) { + console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); + } + }; + uploadTask.on('complete', upCompleteCallback); + + let upFailCallback = (taskStates) => { + for (let i = 0; i < taskStates.length; i++ ) { + console.info("upOnFail taskState:" + JSON.stringify(taskStates[i])); + } + }; + uploadTask.on('fail', upFailCallback); + ``` + + +### off('progress') + +off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) => void): void + +Unsubscribes from upload progress events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| +| callback | function | No| Callback used to return the result.
**uploadedSize**: size of the uploaded files, in bytes.
**totalSize**: Total size of the files to upload, in bytes. | + +**Example** + + ```js + let upProgressCallback = (uploadedSize, totalSize) => { + console.info('Upload delete progress notification.' + 'totalSize:' + totalSize + 'uploadedSize:' + uploadedSize); + }; + uploadTask.off('progress', upProgressCallback); + ``` + + +### off('headerReceive')7+ + +off(type: 'headerReceive', callback?: (header: object) => void): void + +Unsubscribes from HTTP header events for an upload task. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).| +| callback | function | No| Callback used to return the result.
**header**: HTTP response header.| + +**Example** + + ```js + let headerCallback = (header) => { + console.info(`Upload delete headerReceive notification. header: ${JSON.stringify(header)}`); + }; + uploadTask.off('headerReceive', headerCallback); + ``` + +### off('complete' | 'fail')9+ + + off(type:'complete' | 'fail', callback?: Callback<Array<TaskState>>): void; + +Unsubscribes from upload completion or failure events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| +| callback | Callback<Array<TaskState>> | No| Callback used to return the result.
**taskstates**: upload task result.| + +**Example** + + ```js + let upCompleteCallback = (taskStates) => { + console.info('Upload delete complete notification.'); + for (let i = 0; i < taskStates.length; i++ ) { + console.info('taskState:' + JSON.stringify(taskStates[i])); + } + }; + uploadTask.off('complete', upCompleteCallback); + + let upFailCallback = (taskStates) => { + console.info('Upload delete fail notification.'); + for (let i = 0; i < taskStates.length; i++ ) { + console.info('taskState:' + JSON.stringify(taskStates[i])); + } + }; + uploadTask.off('fail', upFailCallback); + ``` + +### delete9+ +delete(): Promise<boolean> + +Deletes this upload task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.| + +**Example** + + ```js + uploadTask.delete().then((result) => { + if (result) { + console.info('Upload task removed successfully. '); + } else { + console.error('Failed to remove the upload task. '); + } + }).catch((err) => { + console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); + }); + ``` + + +### delete9+ + +delete(callback: AsyncCallback<boolean>): void + +Deletes this upload task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| + +**Example** + + ```js + uploadTask.delete((err, result) => { + if (err) { + console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Upload task removed successfully.'); + } else { + console.error('Failed to remove the upload task.'); + } + }); + ``` + + +## UploadConfig +Describes the configuration for an upload task. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| Resource URL.| +| header | Object | Yes| HTTP or HTTPS header added to an upload request.| +| method | string | Yes| Request method, which can be **'POST'** or **'PUT'**. The default value is **'POST'**.| +| files | Array<[File](#file)> | Yes| List of files to upload, which is submitted through **multipart/form-data**.| +| data | Array<[RequestData](#requestdata)> | Yes| Form data in the request body.| +| index20+ | number | No| Path index of the task. The default value is **0**.| +| begins20+ | number | No| Start point of the file read when the upload task begins. The default value is **0**. The value is a closed interval, indicating that the file is read from the beginning.| +| ends20+ | number | No| End point of the file read when the upload task is complete. The default value is **-1**. The value is a closed interval, indicating that the file is read till the end.| + +## TaskState9+ +Implements a **TaskState** object, which is the callback parameter of the [on('complete' | 'fail')9+](#oncomplete--fail9) and [off('complete' | 'fail')9+](#offcomplete--fail9) APIs. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| path | string | Yes| File path.| +| responseCode | number | Yes| Return value of an upload task.| +| message | string | Yes| Description of the upload task result.| + +## File +Describes the list of files in [UploadConfig](#uploadconfig). + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| filename | string | Yes| File name in the header when **multipart** is used.| +| name | string | Yes| Name of a form item when **multipart** is used. The default value is **file**.| +| uri | string | Yes| Local path for storing files.
Only the **internal** protocol type is supported. In the value, **internal://cache/** is mandatory. Example:
internal://cache/path/to/file.txt | +| type | string | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| + + +## RequestData +Describes the form data in [UploadConfig](#uploadconfig). + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of a form element.| +| value | string | Yes| Value of a form element.| + +## request.downloadFile9+ + +downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> + +Downloads files. This API uses a promise to return the result. You can use [on('complete'|'pause'|'remove')7+](#oncompletepauseremove7) to obtain the download task state, which can be completed, paused, or removed. You can also use [on('fail')7+](#onfail7) to obtain the task download error information. + + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | file operation error. | +| 13400002 | bad file path. | +| 13400003 | task manager service error. | + +**Example** + + ```js + let downloadTask; + try { + request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + downloadTask = data; + }).catch((err) => { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + }) + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } + ``` + + +## request.downloadFile9+ + +downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; + +Downloads files. This API uses an asynchronous callback to return the result. You can use [on('complete'|'pause'|'remove')7+](#oncompletepauseremove7) to obtain the download task state, which can be completed, paused, or removed. You can also use [on('fail')7+](#onfail7) to obtain the task download error information. + + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | file operation error. | +| 13400002 | bad file path. | +| 13400003 | task manager service error. | + +**Example** + + ```js + let downloadTask; + try { + request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + filePath: 'xxx/xxxxx.hap'}, (err, data) => { + if (err) { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + return; + } + downloadTask = data; + }); + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } + ``` + +## DownloadTask + +Implements file downloads. Before using any APIs of this class, you must obtain a **DownloadTask** object through [request.downloadFile9+](#requestdownloadfile9) in promise mode or [request.downloadFile9+](#requestdownloadfile9-1) in callback mode. + + +### on('progress') + +on(type: 'progress', callback:(receivedSize: number, totalSize: number) => void): void + +Subscribes to download progress events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| +| callback | function | Yes| Callback used to return the result.| + + Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| receivedSize | number | Yes| Size of the downloaded files, in bytes.| +| totalSize | number | Yes| Total size of the files to download, in bytes.| + +**Example** + + ```js + let progresCallback = (receivedSize, totalSize) => { + console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); + }; + downloadTask.on('progress', progresCallback); + ``` + + +### off('progress') + +off(type: 'progress', callback?: (receivedSize: number, totalSize: number) => void): void + +Unsubscribes from download progress events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| +| callback | function | No| Callback used to return the result.
**receivedSize**: size of the downloaded files.
**totalSize**: total size of the files to download.| + +**Example** + + ```js + let progresCallback = (receivedSize, totalSize) => { + console.info('Download delete progress notification.' + 'receivedSize:' + receivedSize + 'totalSize:' + totalSize); + }; + downloadTask.off('progress', progresCallback); + ``` + + +### on('complete'|'pause'|'remove')7+ + +on(type: 'complete'|'pause'|'remove', callback:() => void): void + +Subscribes to download events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | Yes| Callback used to return the result.| + +**Example** + + ```js + let completeCallback = () => { + console.info('Download task completed.'); + }; + downloadTask.on('complete', completeCallback); + + let pauseCallback = () => { + console.info('Download task pause.'); + }; + downloadTask.on('pause', pauseCallback); + + let removeCallback = () => { + console.info('Download task remove.'); + }; + downloadTask.on('remove', removeCallback); + ``` + + +### off('complete'|'pause'|'remove')7+ + +off(type: 'complete'|'pause'|'remove', callback?:() => void): void + +Unsubscribes from download events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | No| Callback used to return the result.| + +**Example** + + ```js + let completeCallback = () => { + console.info('Download delete complete notification.'); + }; + downloadTask.off('complete', completeCallback); + + let pauseCallback = () => { + console.info('Download delete pause notification.'); + }; + downloadTask.off('pause', pauseCallback); + + let removeCallback = () => { + console.info('Download delete remove notification.'); + }; + downloadTask.off('remove', removeCallback); + ``` + + +### on('fail')7+ + +on(type: 'fail', callback: (err: number) => void): void + +Subscribes to download failure events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| +| callback | function | Yes| Callback for the download task failure event.| + + Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| err | number | Yes| Error code of the download failure. For details about the error codes, see [Download Error Codes](#download-error-codes).| + +**Example** + + ```js + let failCallback = (err) => { + console.info('Download task failed. Cause:' + err); + }; + downloadTask.on('fail', failCallback); + ``` + + +### off('fail')7+ + +off(type: 'fail', callback?: (err: number) => void): void + +Unsubscribes from download failure events. This API uses a callback to return the result synchronously. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| +| callback | function | No| Callback used to return the result.
**err**: error code of the download failure. | + +**Example** + + ```js + let failCallback = (err) => { + console.info(`Download delete fail notification. err: ${err.message}`); + }; + downloadTask.off('fail', failCallback); + ``` + +### delete9+ + +delete(): Promise<boolean> + +Removes this download task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result.| + +**Example** + + ```js + downloadTask.delete().then((result) => { + if (result) { + console.info('Download task removed.'); + } else { + console.error('Failed to remove the download task.'); + } + }).catch ((err) => { + console.error('Failed to remove the download task.'); + }); + ``` + + +### delete9+ + +delete(callback: AsyncCallback<boolean>): void + +Deletes this download task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task deletion result.| + +**Example** + + ```js + downloadTask.delete((err, result)=>{ + if(err) { + console.error('Failed to remove the download task.'); + return; + } + if (result) { + console.info('Download task removed.'); + } else { + console.error('Failed to remove the download task.'); + } + }); + ``` + + +### getTaskInfo9+ + +getTaskInfo(): Promise<DownloadInfo> + +Obtains the information about this download task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information.| + +**Example** + + ```js + downloadTask.getTaskInfo().then((downloadInfo) => { + console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) + }) .catch((err) => { + console.error('Failed to query the download task. Cause:' + err) + }); + ``` + + +### getTaskInfo9+ + +getTaskInfo(callback: AsyncCallback<DownloadInfo>): void + +Obtains the information about this download task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| + +**Example** + + ```js + downloadTask.getTaskInfo((err, downloadInfo)=>{ + if(err) { + console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); + } else { + console.info('download query success. data:'+ JSON.stringify(downloadInfo)); + } + }); + ``` + + +### getTaskMimeType9+ + +getTaskMimeType(): Promise<string> + +Obtains the **MimeType** of this download task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the **MimeType** of the download task.| + +**Example** + + ```js + downloadTask.getTaskMimeType().then((data) => { + console.info('Download task queried. Data:' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) + }); + ``` + + +### getTaskMimeType9+ + +getTaskMimeType(callback: AsyncCallback<string>): void; + +Obtains the **MimeType** of this download task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| + +**Example** + + ```js + downloadTask.getTaskMimeType((err, data)=>{ + if(err) { + console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); + } else { + console.info('Download task queried. data:' + JSON.stringify(data)); + } + }); + ``` + + +### suspend9+ + +suspend(): Promise<boolean> + +Pauses this download task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the download task pause result.| + +**Example** + + ```js + downloadTask.suspend().then((result) => { + if (result) { + console.info('Download task paused. '); + } else { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); + } + }).catch((err) => { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); + }); + ``` + + +### suspend9+ + +suspend(callback: AsyncCallback<boolean>): void + +Pauses this download task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| + +**Example** + + ```js + downloadTask.suspend((err, result)=>{ + if(err) { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Download task paused. '); + } else { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); + } + }); + ``` + + +### restore9+ + +restore(): Promise<boolean> + +Resumes this download task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + + ```js + downloadTask.restore().then((result) => { + if (result) { + console.info('Download task resumed.') + } else { + console.error('Failed to resume the download task. '); + } + console.info('Download task resumed.') + }).catch((err) => { + console.error('Failed to resume the download task. Cause:' + err); + }); + ``` + + +### restore9+ + +restore(callback: AsyncCallback<boolean>): void + +Resumes this download task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| + +**Example** + + ```js + downloadTask.restore((err, result)=>{ + if (err) { + console.error('Failed to resume the download task. Cause:' + err); + return; + } + if (result) { + console.info('Download task resumed.'); + } else { + console.error('Failed to resume the download task.'); + } + }); + ``` + +## DownloadConfig +Defines the download task configuration. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| Resource URL.| +| header | Object | No| HTTPS flag header to be included in the download request.
The **X-TLS-Version** parameter in **header** specifies the TLS version to be used. If this parameter is not set, the CURL_SSLVERSION_TLSv1_2 version is used. Available options are as follows:
CURL_SSLVERSION_TLSv1_0
CURL_SSLVERSION_TLSv1_1
CURL_SSLVERSION_TLSv1_2
CURL_SSLVERSION_TLSv1_3
The **X-Cipher-List** parameter in **header** specifies the cipher suite list to be used. If this parameter is not specified, the secure cipher suite list is used. Available options are as follows:
- The TLS 1.2 cipher suite list includes the following ciphers:
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,TLS_DSS_RSA_WITH_AES_256_GCM_SHA384,
TLS_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,
TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_128_CCM,
TLS_DHE_RSA_WITH_AES_256_CCM,TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
TLS_PSK_WITH_AES_256_CCM,TLS_DHE_PSK_WITH_AES_128_CCM,
TLS_DHE_PSK_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
TLS_ECDHE_ECDSA_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
- The TLS 1.3 cipher suite list includes the following ciphers:
TLS_AES_128_GCM_SHA256,TLS_AES_256_GCM_SHA384,TLS_CHACHA20_POLY1305_SHA256,TLS_AES_128_CCM_SHA256
- The TLS 1.3 cipher suite list adds the Chinese national cryptographic algorithm:
TLS_SM4_GCM_SM3,TLS_SM4_CCM_SM3 | +| enableMetered | boolean | No| Whether download is allowed on a metered connection. The default value is **false**. In general cases, a mobile data connection is metered, while a Wi-Fi connection is not.
- **true**: allowed
- **false**: not allowed| +| enableRoaming | boolean | No| Whether download is allowed on a roaming network. The default value is **false**.
- **true**: allowed
- **false**: not allowed| +| description | string | No| Description of the download session.| +| filePath7+ | string | No| Path where the downloaded file is stored.
- In the FA model, use [context](js-apis-inner-application-context.md) to obtain the cache directory of the application, for example, **\${featureAbility.getContext().getFilesDir()}/test.txt\**, and store the file in this directory.
- In the stage model, use [AbilityContext](js-apis-inner-application-context.md) to obtain the file path, for example, **\${globalThis.abilityContext.tempDir}/test.txt\**, and store the file in this path.| +| networkType | number | No| Network type allowed for download. The default value is **NETWORK_MOBILE and NETWORK_WIFI**.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000| +| title | string | No| Download task name.| +| background9+ | boolean | No| Whether to enable background task notification so that the download status is displayed in the notification panel. The default value is false.| + + +## DownloadInfo7+ +Defines the download task information, which is the callback parameter of the [getTaskInfo9+](#gettaskinfo9) API. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +| Name| Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| downloadId | number |Yes| ID of the download task.| +| failedReason | number|Yes| Cause of the download failure. The value can be any constant in [Download Error Codes](#download-error-codes).| +| fileName | string |Yes| Name of the downloaded file.| +| filePath | string |Yes| URI of the saved file.| +| pausedReason | number |Yes| Cause of download pause. The value can be any constant in [Causes of Download Pause](#causes-of-download-pause).| +| status | number |Yes| Download task status code. The value can be any constant in [Download Task Status Codes](#download-task-status-codes).| +| targetURI | string |Yes| URI of the downloaded file.| +| downloadTitle | string |Yes| Name of the download task.| +| downloadTotalBytes | number |Yes| Total size of the files to download, in bytes.| +| description | string |Yes| Description of the download task.| +| downloadedBytes | number |Yes| Size of the files downloaded, in bytes.| + +## Action10+ + +Defines action options. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Value | Description | +| -------- | ----- | ----------- | +| DOWNLOAD | 0 | Download. | +| UPLOAD | 1 | Upload. | + + +## Mode10+ + +Defines mode options. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Value | Description | +| ---------- | ----- | ---------------- | +| FOREGROUND | 0 | Foreground task. | + +## Network10+ + +Defines network options. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Value | Description | +| -------- | ----- | ---------------------- | +| ANY | 0 | Network of any type. | +| WIFI | 1 | Wi-Fi network. | +| CELLULAR | 2 | Cellular data network. | + + +## FormItem10+ + +Describes the form item of a task. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| ----- | ------------------------------------------------------------ | --------- | --------------------- | +| name | string | Yes | Form parameter name. | +| value | string \| [FileSpec](#filespec10) \| Array<[FileSpec](#filespec10)> | Yes | Form parameter value. | + + +## Config10+ + +Provides the configuration information of an upload or download task. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ | +| action | [Action](#action10) | Yes | Task action.
- **UPLOAD**
- **DOWNLOAD** | +| url | string | Yes | Resource URL. The value contains a maximum of 2048 characters. | +| title | string | No | Task title. The value contains a maximum of 256 characters. The default value is a null string. | +| description | string | No | Task description. The value contains a maximum of 1024 characters. The default value is a null string. | +| mode | [Mode](#mode10) | No | Task mode. The default mode is foreground .
- For a foreground task, a callback is used for notification. | +| overwrite | boolean | No | Whether to overwrite an existing file during the download. The default value is **false**.
- **true**: Overwrite the existing file.
- **false**: Do not overwrite the existing file. In this case, the download fails. | +| method | string | No | Standard HTTP method for the task. The value can be **GET**, **POST**, or **PUT**, which is case-insensitive.
- If the task is an upload, use **PUT** or **POST**. The default value is **PUT**.
- If the task is a download, use **GET** or **POST**. The default value is **GET**. | +| headers | object | No | HTTP headers to be included in the task.
- If the task is an upload, the default **Content-Type** is **multipart/form-data**.
- If the task is a download, the default **Content-Type** is **application/json**. | +| data | string \| Array<[FormItem](#formitem10)> | No | Task data.
- If the task is a download, the value is a string, typically in JSON format (an object will be converted to a JSON string); the default value is null.
- If the task is an upload, the value is Array<[FormItem](#formitem10)>; the default value is null. | +| saveas | string | No | Path for storing downloaded files. The options are as follows:
- Relative path in the cache folder of the invoker, for example, **"./xxx/yyy/zzz.html"** and **"xxx/yyy/zzz.html"**.
- URI (applicable when the application has the permission to access the URI), for example, **"datashare://bundle/xxx/yyy/zzz.html"**. This option is not supported currently.
The default value is a relative path in the cache folder of the application. | +| network | [Network](#network10) | No | Network used for the task. The default value is **ANY** (Wi-Fi or cellular). | +| metered | boolean | No | Whether the task is allowed on a metered connection. The default value is **false**.
- **true**: The task is allowed on a metered connection.
- **false**: The task is not allowed on a metered connection. | +| roaming | boolean | No | Whether the task is allowed on a roaming network. The default value is **true**.
- **true**: The task is allowed on a roaming network.
- **false**: The task is not allowed on a roaming network. | +| redirect | boolean | No | Whether redirection is allowed. The default value is **true**.
- **true**: Redirection is allowed.
- **false**: Redirection is not allowed. | +| index | number | No | Path index of the task. It is usually used for resumable downloads. The default value is **0**. | +| begins | number | No | File start point of the task. It is usually used for resumable downloads. The default value is **0**. The value is a closed interval.
- If the task is a download, the value is obtained by sending an HTTP range request to read the start position when the server starts to download files.
- If the task is an upload, the value is obtained at the beginning of the upload. | +| ends | number | No | File end point of the task. It is usually used for resumable downloads. The default value is **-1**. The value is a closed interval.
- If the task is a download, the value is obtained by sending an HTTP range request to read the end position when the server starts to download files.
- If the task is an upload, the value is obtained at the end of the upload. | +| precise | boolean | No | - If this parameter is set to **true**, the task fails when the file size cannot be obtained.
- If this parameter is set to **false**, the task continues when the file size is set to **-1**.
The default value is **false**. | +| token | string | No | Token of the task. If the task has a token configured, this token is required for query of the task. The value contains 8 to 2048 bytes. This parameter is left empty by default. | +| extras | object | No | Additional information of the task. This parameter is left empty by default. | +| proxy20+ | string | No| Proxy address. The value contains a maximum of 512 characters.
It is in the format of http://\:\. By default, this parameter is left blank.| + +## State10+ + +Defines the current task status. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Value | Description | +| ----------- | ----- | ------------------------------------------------------------ | +| INITIALIZED | 0x00 | The task is initialized based on the configuration specified in [Config](#config10). | +| WAITING | 0x10 | The task lacks resources for running or the resources for retries do not match the network status. | +| RUNNING | 0x20 | The task is being executed. | +| RETRYING | 0x21 | The task has failed at least once and is being executed again. | +| PAUSED | 0x30 | The task is suspended and will be resumed later. | +| STOPPED | 0x31 | The task is stopped. | +| COMPLETED | 0x40 | The task is complete. | +| FAILED | 0x41 | The task fails. | +| REMOVED | 0x50 | The task is removed. | + + +## Progress10+ + +Describes the data structure of the task progress. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| --------- | ------------------- | --------- | ------------------------------------------------------------ | +| state | [State](#state10) | Yes | Current task status. | +| index | number | Yes | Index of the file that is being processed in the task. | +| processed | number | Yes | Size of processed data in the current file in the task, in bytes. | +| sizes | Array<number> | Yes | Size of files in the task, in bytes. | +| extras | object | No | Extra information of the task, for example, the header of the response from the server. | + + +## Faults10+ + +Defines the cause of a task failure. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Value | Description | +| ------------ | ----- | ------------------------------------------------------------ | +| OTHERS | 0xFF | Other fault. | +| DISCONNECTED | 0x00 | Network disconnection. | +| TIMEOUT | 0x10 | Timeout. | +| PROTOCOL | 0x20 | Protocol error, for example, an internal server error (500) or a data range that cannot be processed (416). | +| FSIO | 0x40 | File system I/O error, for example, an error that occurs during the open, search, read, write, or close operation. | + + +## Filter10+ + +Defines the filter criteria. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| ------ | ------------------- | --------- | ------------------------------------------------------------ | +| before | number | No | Unix timestamp of the end time, in milliseconds. The default value is the invoking time. | +| after | number | No | Unix timestamp of the start time, in milliseconds. The default value is the invoking time minus 24 hours. | +| state | [State](#state10) | No | Task state. | +| action | [Action](#action10) | No | Task action.
- **UPLOAD**
- **DOWNLOAD** | +| mode | [Mode](#mode10) | No | Task mode.
- **FOREGROUND** | + +## TaskInfo10+ + +Defines the data structure of the task information for query. The fields available vary depending on the query type. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ | +| saveas | string | No | Path for storing downloaded files. The options are as follows:
- Relative path in the cache folder of the invoker, for example, **"./xxx/yyy/zzz.html"** and **"xxx/yyy/zzz.html"**.
- URI (applicable when the application has the permission to access the URI), for example, **"datashare://bundle/xxx/yyy/zzz.html"**. This option is not supported currently.
The default value is a relative path in the cache folder of the application. | +| url | string | No | Task URL.
- It can be obtained through [request.agent.show10+](#requestagentshow10-1), [request.agent.touch10+](#requestagenttouch10-1), or [request.agent.query10+](#requestagentquery10-1). When [request.agent.query10+](#requestagentquery10-1) is used, an empty string is returned. | +| data | string \| Array<[FormItem](#formitem10)> | No | Task value.
- It can be obtained through [request.agent.show10+](#requestagentshow10-1), [request.agent.touch10+](#requestagenttouch10-1), or [request.agent.query10+](#requestagentquery10-1). When [request.agent.query10+](#requestagentquery10-1) is used, an empty string is returned. | +| tid | string | Yes | Task ID. | +| title | string | Yes | Task title. | +| description | string | Yes | Task description. | +| action | [Action](#action10) | Yes | Task action.
- **UPLOAD**
- **DOWNLOAD** | +| mode | [Mode](#mode10) | Yes | Task mode.
- **FOREGROUND** | +| mimeType | string | Yes | MIME type in the task configuration. | +| progress | [Progress](#progress10) | Yes | Task progress. | +| ctime | number | Yes | Unix timestamp when the task is created, in milliseconds. The value is generated by the system of the current device.
Note: When [request.agent.search10+](#requestagentsearch10-1) is used for query, this value must be within the range of [after,before] for the task ID to be obtained. For details about **before** and **after**, see [Filter](#filter10). | +| mtime | number | Yes | Unix timestamp when the task state changes, in milliseconds. The value is generated by the system of the current device. | +| faults | [Faults](#faults10) | Yes | Failure cause of the task.
- **OTHERS**: other fault.
- **DISCONNECT**: network disconnection.
- **TIMEOUT**: timeout.
- **PROTOCOL**: protocol error.
- **FSIO**: file system I/O error. | +| reason | string | Yes | Reason why the task is waiting, failed, stopped, or paused. | +| extras | string | No | Extra information of the task | +| priority20+ | number | Yes| Task priority. The priority of a foreground task is higher than that of a background task. For tasks in the same mode, a smaller value indicates a higher priority.| + +## HttpResponse20+ +Describes the data structure of the task response header. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| version | string | Yes| HTTP version.| +| statusCode | number | Yes| HTTP response status code.| +| reason | string | Yes| HTTP response cause.| +| headers | Map<string, Array<string>> | Yes| HTTP response header.| + +## BroadcastEvent20+ + +Defines a custom system event. You can use a common event API to obtain the event. +The upload and download SA has the ohos.permission.SEND_TASK_COMPLETE_EVENT permission. You can configure the level-2 configuration file to which the metadata of an event points to intercept other event senders. + +Use the **CommonEventData** type to transmit data related to common events. The members in **CommonEventData** are different from those described in [CommonEventData](js-apis-inner-commonEvent-commonEventData.md). Specifically, **CommonEventData.code** indicates the task status, which is **0x40 COMPLETE** or **0x41 FAILED**, and **CommonEventData.data** indicates the task ID. + + +For details about how to obtain the event configuration and configure the level-2 configuration file, see [Subscribing to Common Events in Static Mode (for System Applications Only)](../../basic-services/common-event/common-event-static-subscription.md). + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name| Value| Description | +| -------- | ------- |-----------| +| COMPLETE | 'ohos.request.event.COMPLETE' | Task completion event. The returned event code can be **0x40** or **0x41**, depending on whether the task is successful or fails.| + + +## Task10+ + +Implements an upload or download task. Before using this API, you must obtain a **Task** object, from a promise through [request.agent.create10+](#requestagentcreate10-1) or from a callback through [request.agent.create10+](#requestagentcreate10). + +### Attributes + +Task attributes include the task ID and task configuration. + +**System capability**: SystemCapability.Request.FileTransferAgent + +| Name | Type | Mandatory | Description | +| ------ | ------------------- | --------- | ------------------------------------------------------------ | +| tid | string | Yes | Task ID, which is unique in the system and is automatically generated by the system. | +| config | [Config](#config10) | Yes | Task configuration. | + + +### on('progress')10+ + +on(event: 'progress', callback: (progress: Progress) => void): void + +Subscribes to foreground task progress changes. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'progress'**, indicating the task progress. | +| callback | function | Yes | Callback used to return the data structure of the task progress. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + mimeType: "application/octet-stream", + path: "./taskOnTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task progress.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('progress', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('completed')10+ + +on(event: 'completed', callback: (progress: Progress) => void): void + +Subscribes to the foreground task completion event. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'completed'**, indicating task completion. | +| callback | function | Yes | Callback used to return the data structure of the task progress. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + mimeType: "application/octet-stream", + path: "./taskOnTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task completed.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('completed', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('failed')10+ + +on(event: 'failed', callback: (progress: Progress) => void): void + +Subscribes to the foreground task failure event. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'failed'**, indicating task failure. | +| callback | function | Yes | Callback used to return the data structure of the task progress. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + mimeType: "application/octet-stream", + path: "./taskOnTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task failed.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('failed', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('response')20+ + +on(event: 'response', callback: Callback<HttpResponse>): void + +Subscribes to task response headers. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
- **'response'**: task response.| +| callback | Callback<[HttpResponse](#httpresponse12)> | Yes| Callback used to return the data structure of the task response header.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + path: "./taskOnTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (response: request.agent.HttpResponse) => { + console.info('upload task response.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('response', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('pause')20+ + +on(event: 'pause', callback: (progress: [Progress](#progress10)) => void): void + +Subscribes to task pause events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
- **'pause'**: task pause.| +| callback | function | Yes| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + path: "./taskOnTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task pause.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('pause', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('resume')20+ + +on(event: 'resume', callback: (progress: [Progress](#progress10)) => void): void + +Subscribes to task resume events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
- **'resume'**: task resume.| +| callback | function | Yes| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + path: "./taskOnTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task resume.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('resume', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.resume(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### on('remove')20+ + +on(event: 'remove', callback: (progress: [Progress](#progress10)) => void): void + +Subscribes to task removal events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to subscribe to.
- **'remove'**: task removal.| +| callback | function | Yes| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOnTest", + value: { + filename: "taskOnTest.avi", + path: "./taskOnTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOnTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOnCallback = (progress: request.agent.Progress) => { + console.info('upload task remove.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('remove', createOnCallback); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + request.agent.remove(task.tid); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + + + +### off('progress')10+ + +off(event: 'progress', callback?: (progress: Progress) => void): void + +Unsubscribes from foreground task progress changes. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'progress'**, indicating the task progress. | +| callback | function | No | Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + mimeType: "application/octet-stream", + path: "./taskOffTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task progress.'); +}; +let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task progress.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('progress', createOffCallback1); + task.on('progress', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('progress', createOffCallback1); + // Unsubscribe from all callbacks of foreground task progress changes. + task.off('progress'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('completed')10+ + +off(event: 'completed', callback?: (progress: Progress) => void): void + +Unsubscribes from the foreground task completion event. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'completed'**, indicating task completion. | +| callback | function | No | Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + mimeType: "application/octet-stream", + path: "./taskOffTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task completed.'); +}; +let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task completed.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('completed', createOffCallback1); + task.on('completed', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('completed', createOffCallback1); + // Unsubscribe from all callbacks of the foreground task completion event. + task.off('completed'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('failed')10+ + +off(event: 'failed', callback?: (progress: Progress) => void): void + +Unsubscribes from the foreground task failure event. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| event | string | Yes | Type of the event to subscribe to.
The value is **'failed'**, indicating task failure. | +| callback | function | No | Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------- | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + mimeType: "application/octet-stream", + path: "./taskOffTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task failed.'); +}; +let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task failed.'); +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.on('failed', createOffCallback1); + task.on('failed', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('failed', createOffCallback1); + // Unsubscribe from all callbacks of the foreground task failure event. + task.off('failed'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('response')20+ + +off(event: 'response', callback?: Callback<HttpResponse>): void + +Unsubscribes from task response headers. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to unsubscribe from.
- **response**: task response.| +| callback | Callback<[HttpResponse](#httpresponse12)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the current type will be unregistered.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + path: "./taskOffTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOffCallback1 = (progress: request.agent.HttpResponse) => { + console.info('upload task response.'); + }; + let createOffCallback2 = (progress: request.agent.HttpResponse) => { + console.info('upload task response.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('response', createOffCallback1); + task.on('response', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('response', createOffCallback1); + // Unsubscribe from all callbacks of the task removal event. + task.off('response'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('pause')20+ + +off(event: 'pause', callback?: (progress: [Progress](#progress10)) => void): void + +Unsubscribes from the foreground task pause event. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to unsubscribe from.
- **'pause'**: task pause.| +| callback | function | No| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + path: "./taskOffTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task pause.'); + }; + let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task pause.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('pause', createOffCallback1); + task.on('pause', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('pause', createOffCallback1); + // Unsubscribe from all callbacks of the foreground task pause event. + task.off('pause'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('resume')20+ + +off(event: 'resume', callback?: (progress: [Progress](#progress10)) => void): void + +Unsubscribes from the foreground task resume event. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to unsubscribe from.
- **'resume'**: task resume.| +| callback | function | No| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + path: "./taskOffTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task resume.'); + }; + let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task resume.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('resume', createOffCallback1); + task.on('resume', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('resume', createOffCallback1); + // Unsubscribe from all callbacks of the foreground task resume event. + task.off('resume'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### off('remove')20+ + +off(event: 'remove', callback?: (progress: [Progress](#progress10)) => void): void + +Unsubscribes from the task removal event. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Type of the event to unsubscribe from.
- **'remove'**: task removal.| +| callback | function | No| Callback used to return the data structure of the task progress.| + +Parameters of the callback function + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| progress | [Progress](#progress10) | Yes| Task progress.| + +**Error codes** + +For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 401 | Parameter error. Possible causes: 1. Missing mandatory parameters. 2. Incorrect parameter type. 3. Parameter verification failed. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let attachments: Array = [{ + name: "taskOffTest", + value: { + filename: "taskOffTest.avi", + path: "./taskOffTest.avi", + } + }]; + let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskOffTest', + description: 'Sample code for event listening', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + let createOffCallback1 = (progress: request.agent.Progress) => { + console.info('upload task remove.'); + }; + let createOffCallback2 = (progress: request.agent.Progress) => { + console.info('upload task remove.'); + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.on('remove', createOffCallback1); + task.on('remove', createOffCallback2); + // Unsubscribe from createOffCallback1. + task.off('remove', createOffCallback1); + // Unsubscribe from all callbacks of the task removal event. + task.off('remove'); + console.info(`Succeeded in creating a upload task. result: ${task.tid}`); + task.start(); + }).catch((err: BusinessError) => { + console.error(`Failed to create a upload task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### start10+ + +start(callback: AsyncCallback<void>): void + +Starts this task. This API cannot be used to start an initialized task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| callback | function | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```ts +let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStartTest', + description: 'Sample code for start the download task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.start((err: BusinessError) => { + if (err) { + console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in starting a download task.`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### start10+ + +start(): Promise<void> + +Starts this task. This API cannot be used to start an initialized task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```ts +let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStartTest', + description: 'Sample code for start the download task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.start().then(() => { + console.info(`Succeeded in starting a download task.`); + }).catch((err: BusinessError) => { + console.error(`Failed to start the download task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +### pause20+ + +pause(callback: AsyncCallback<void>): void + +Pauses a task that is waiting, running, or retrying. A paused task can be resumed by [resume](#resume10). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | Task service ability error. | +| 21900007 | Operation with wrong task state. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskPauseTest', + description: 'Sample code for pause the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause((err: BusinessError) => { + if (err) { + console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in pausing a download task. `); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +### pause20+ + +pause(): Promise<void> + +Pauses a task that is waiting, running, or retrying. A paused task can be resumed by [resume](#resume10). This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400003 | Task service ability error. | +| 21900007 | Operation with wrong task state. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskPauseTest', + description: 'Sample code for pause the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause().then(() => { + console.info(`Succeeded in pausing a download task. `); + }).catch((err: BusinessError) => { + console.error(`Failed to pause the download task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` +### resume20+ + +resume(callback: AsyncCallback<void>): void + +Resumes a paused task. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission denied. | +| 13400003 | Task service ability error. | +| 21900007 | Operation with wrong task state. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskResumeTest', + description: 'Sample code for resume the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.resume((err: BusinessError) => { + if (err) { + console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in resuming a download task. `); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +### resume20+ + +resume(): Promise<void> + +Resumes a paused task. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](errorcode-request.md) and [Universal Error Codes](../errorcode-universal.md). + +| ID| Error Message| +| -------- | -------- | +| 201 | Permission denied. | +| 13400003 | Task service ability error. | +| 21900007 | Operation with wrong task state. | + +**Example** + + ```ts + import { BusinessError } from '@kit.BasicServicesKit'; + import { common } from '@kit.AbilityKit'; + + // Obtain the context from the component and ensure that the return value of this.getUIContext().getHostContext() is UIAbilityContext. + let context = this.getUIContext().getHostContext() as common.UIAbilityContext; + let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', // Replace the URL with the HTTP address of the real server. + title: 'taskResumeTest', + description: 'Sample code for resume the download task', + mode: request.agent.Mode.BACKGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" + }; + request.agent.create(context, config).then((task: request.agent.Task) => { + task.start(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.pause(); + for(let t = Date.now(); Date.now() - t <= 1000;); // To prevent asynchronous out-of-order, wait for 1 second before performing the next operation. + task.resume().then(() => { + console.info(`Succeeded in resuming a download task. `); + }).catch((err: BusinessError) => { + console.error(`Failed to resume the download task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); + }).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + }); + ``` + +### stop10+ + +stop(callback: AsyncCallback<void>): void + +Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| callback | function | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```ts +let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStopTest', + description: 'Sample code for stop the download task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.stop((err: BusinessError) => { + if (err) { + console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in stopping a download task. `); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + + +### stop10+ + +stop(): Promise<void> + +Stops this task. This API can be used to stop a running, waiting, or retrying task. This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900007 | task state error. | + +**Example** + + ```ts +let config: request.agent.Config = { + action: request.agent.Action.DOWNLOAD, + url: 'http://127.0.0.1', + title: 'taskStopTest', + description: 'Sample code for stop the download task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "GET", + data: "", + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + task.stop().then(() => { + console.info(`Succeeded in stopping a download task. `); + }).catch((err: BusinessError) => { + console.error(`Failed to stop the download task, Code: ${err.code}, message: ${err.message}`); + }); + console.info(`Succeeded in creating a download task. result: ${task.tid}`); +}).catch((err: BusinessError) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +## request.agent.create10+ + +create(context: BaseContext, config: Config, callback: AsyncCallback<Task>): void + +Creates an upload or download task and adds it to the queue. An application can create a maximum of 10 unfinished tasks. This API uses an asynchronous callback to return the result. + + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ------------------------------------------------------------ | +| config | [Config](#config10) | Yes | Task configuration. | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes | Application-based context. | +| callback | AsyncCallback<[Task](#task10)> | Yes | Callback used to return the configuration about the created task. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------------------------- | +| 13400001 | file operation error. | +| 13400003 | task service ability error. | +| 21900004 | application task queue full error. | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "createTest", + value: { + filename: "createTest.avi", + mimeType: "application/octet-stream", + path: "./createTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'createTest', + description: 'Sample code for create task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config, (err: BusinessError, task: request.agent.Task) => { + if (err) { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in creating a download task. result: ${task.config}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +## request.agent.create10+ + +create(context: BaseContext, config: Config): Promise<Task> + +Creates an upload or download task and adds it to the queue. An application can create a maximum of 10 unfinished tasks. This API uses a promise to return the result. + + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------------------------- | --------- | -------------------------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes | Application-based context. | +| config | [Config](#config10) | Yes | Task configuration. | + +**Return value** + +| Type | Description | +| ------------------------------ | ------------------------------------------------------------ | +| Promise<[Task](#task10)> | Promise used to return the configuration about the created task. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | ---------------------------------- | +| 13400001 | file operation error. | +| 13400003 | task service ability error. | +| 21900004 | application task queue full error. | +| 21900005 | task mode error. | + +**Example** + + ```ts +let attachments: Array = [{ + name: "createTest", + value: { + filename: "createTest.avi", + mimeType: "application/octet-stream", + path: "./createTest.avi", + } +}]; +let config: request.agent.Config = { + action: request.agent.Action.UPLOAD, + url: 'http://127.0.0.1', + title: 'createTest', + description: 'Sample code for create task', + mode: request.agent.Mode.FOREGROUND, + overwrite: false, + method: "PUT", + data: attachments, + saveas: "./", + network: request.agent.Network.CELLULAR, + metered: false, + roaming: true, + retry: true, + redirect: true, + index: 0, + begins: 0, + ends: -1, + gauge: false, + precise: false, + token: "it is a secret" +}; +request.agent.create(getContext(), config).then((task: request.agent.Task) => { + console.info(`Succeeded in creating a download task. result: ${task.config}`); +}).catch((err) => { + console.error(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + +> **NOTE** +> +> For details about how to obtain the context in the example, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +## request.agent.remove10+ + +remove(id: string, callback: AsyncCallback<void>): void + +Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| id | string | Yes | Task ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.remove("123456", (err: BusinessError) => { + if (err) { + console.error(`Failed to removing a download task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in creating a download task.`); +}); + ``` + + +## request.agent.remove10+ + +remove(id: string): Promise<void> + +Removes a specified task of the invoker. If the task is being executed, the task is forced to stop. This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ----------- | +| id | string | Yes | Task ID. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.remove("123456").then(() => { + console.info(`Succeeded in removing a download task. `); +}).catch((err: BusinessError) => { + console.error(`Failed to remove a download task, Code: ${err.code}, message: ${err.message}`); +}); + ``` + + +## request.agent.show10+ + +show(id: string, callback: AsyncCallback<TaskInfo>): void + +Shows the task details based on the task ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------------- | --------- | ------------------------------------- | +| id | string | Yes | Task ID. | +| callback | AsyncCallback<[TaskInfo](#taskinfo10)> | Yes | Callback used to return task details. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.show("123456", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { + if (err) { + console.error(`Failed to show a upload task, Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in showing a upload task.`); +}); + ``` + + +## request.agent.show10+ + +show(id: string): Promise<TaskInfo> + +Queries a task details based on the task ID. This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ----------- | +| id | string | Yes | Task ID. | + +**Return value** + +| Type | Description | +| -------------------------------------- | -------------------------------------------- | +| Promise<[TaskInfo](#taskinfo10)> | Promise Promise used to return task details. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.show("123456").then((taskInfo: request.agent.TaskInfo) => { + console.info(`Succeeded in showing the upload task.`); +}).catch((err: BusinessError) => { + console.error(`Failed to show the upload task. Code: ${err.code}, message: ${err.message}`); +}); + ``` + + +## request.agent.touch10+ + +touch(id: string, token: string, callback: AsyncCallback<TaskInfo>): void + +Queries the task details based on the task ID and token. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------------- | --------- | ------------------------------------- | +| id | string | Yes | Task ID. | +| token | string | Yes | Token for task query. | +| callback | AsyncCallback<[TaskInfo](#taskinfo10)> | Yes | Callback used to return task details. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.touch("123456", "token", (err: BusinessError, taskInfo: request.agent.TaskInfo) => { + if (err) { + console.error(`Failed to touch an upload task. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Succeeded in touching an upload task.`); +}); + ``` + + +## request.agent.touch10+ + +touch(id: string, token: string): Promise<TaskInfo> + +Queries the task details based on the task ID and token. This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | --------- | --------------------- | +| id | string | Yes | Task ID. | +| token | string | Yes | Token for task query. | + +**Return value** + +| Type | Description | +| -------------------------------------- | -------------------------------------------- | +| Promise<[TaskInfo](#taskinfo10)> | Promise Promise used to return task details. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | +| 21900006 | task not found error. | + +**Example** + + ```ts +request.agent.touch("123456", "token").then((taskInfo: request.agent.TaskInfo) => { + console.info(`Succeeded in touching a upload task. `); +}).catch((err: BusinessError) => { + console.error(`Failed to touch an upload task. Code: ${err.code}, message: ${err.message}`); +}); + ``` + +## request.agent.search10+ + +search(callback: AsyncCallback<Array<string>>): void + +Searches for task IDs based on [Filter](#filter10). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ---------------------------------------- | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return task ID matches. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | + +**Example** + + ```ts +request.agent.search((err: BusinessError, data: Array) => { + if (err) { + console.error(`Upload task search failed. Code: ${err.code}, message: ${err.message}`); + return; + } + console.info(`Upload task search succeeded. `); +}); + ``` + + +## request.agent.search10+ + +search(filter?: Filter): Promise<Array<string>> + +Searches for task IDs based on [Filter](#filter10). This API uses a promise to return the result. + +**System capability**: SystemCapability.Request.FileTransferAgent + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------------------- | --------- | ---------------- | +| filter | [Filter](#filter10) | No | Filter criteria. | + +**Return value** + +| Type | Description | +| ---------------------------------- | ----------------------------------------------- | +| Promise<Array<string>> | Promise Promise used to return task ID matches. | + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID | Error Message | +| -------- | --------------------------- | +| 13400003 | task service ability error. | + +**Example** + + ```ts +let filter: request.agent.Filter = { + bundle: "com.example.myapplication", + action: request.agent.Action.UPLOAD, + mode: request.agent.Mode.FOREGROUND +} +request.agent.search(filter).then((data: Array) => { + console.info(`Upload task search succeeded. `); +}).catch((err: BusinessError) => { + console.error(`Upload task search failed. Code: ${err.code}, message: ${err.message}`); +}); + ``` + + \ No newline at end of file