当前位置:   article > 正文

HarmonyOS开发(九):数据管理_import relationalstore from '@ohos.data.relational

import relationalstore from '@ohos.data.relationalstore';

1、概述

1.1、功能简介

数据管理为开发者提供数据存储、数据管理能力。

它分为两个部分:

  • 数据存储:提供通用数据持久化能力,根据数据特点,分为用户首选项、键值型数据库和关系型数据库。
  • 数据管理:提供高效的数据管理能力,包括权限管理、数据备分恢复、数据共享等

注:应用创建的数据库,都保存到应用少盒,当应用卸载时,数据库也会自动删除。

1.2、运作机制

数据管理模块包括用户首选项、键值型数据管理、关系型数据管理、分布式数据对象和跨应用数据管理。

Interface接口层提供标准JS API接口

Frameworks&System service层负责实现部件数据存储功能

另外还有一些SQLite和其它子系统的依赖

  • 用户首选项:Preferences, 提供轻量级配置数据持久化能力,支持订阅数据变化的通知能力。不支持分布式同步,常常用来保存应用配置信息、用户偏好设置等
  • 键值型数据管理:KV-Store,提供了键值型数据库的读写、加密、手动备份能力。暂不支持分布式功能。
  • 关系型数据管理:RelationalStore,提供了关系型数据库的增删改查、加密、手动备份能力。暂不支持分布式功能。
  • 分布式数据对象:DataObject,独立提供地象型结构数据的分布式能力,暂不支持分布式功能。
  • 跨应用数据管理:DataShare,提供了向其他应用共享以及管理其数据的方法。仅系统应用可用。

2、应用数据持久化概述

应用数据持久化,是指应用将内存中的数据通过文件或数据库的形式保存到设备上。内存中的数据形态通常是任意的数据结构或数据对象,存储介质上的数据形态可能是文本、数据库、二进制文件等。

HarmonyOS标准系统支持典型的存储数据形态有:用户首选项、键值型数据库、关系型数据库

3、用户首选项实现数据持久化

用户首选项为应用提供key-value键值型的数据处理能力,支持应用持久化轻量级数据,并对其进行修改和查询。

Preferences不适合存放过多数据,适用的场景一般为应用保存用户个性化的配置。

3.1、运作机制

用户程序通过JS接口调用用户首选项读写对应的数据文件。开发者可以把用户首选项持久化文件的内容加载到Preferences实例,每个文件唯一对应到一个Preferences实例,系统会通过静态容器把这个实例存储在内存中,直到主动从内存中移除这个实例或删除这个文件。

3.2、使用约束

1、key键为string类型,要求非空且长度不超过80个字节

2、value值为string类型时可以为空,不为空时长度不超过8192个字节

3、内存会随着存储数据量的增大而增大,所以存储的数据应该是轻量级的,建议存储的数据不要超过1万条

3.3、相关接口说明

接口大部分都是异步接口,异步接口都有callback和Promise两种返回形式。以下为callback为例说明

接口名称描述
getPreferences(context:Context,name:string,callback:AsyncCallback<Preferences>):void获取Preferences 实例
put(key:string,value:valueType,callback:AsyncCallback<void>):void把数据写入Preferences实例,可以通过flush把实例进行持 久化
has(key:string,callback:AsyncCallback<boolean>):void检查实例中是否包含指定的key的存储键值对,给定的key不可以为空
get(key:string,defValue:valueType,callback:AsyncCallback<valueType>):void获取指定键对应的值,如果值为null或者非默认值类型,返回默认数据defValue
delete(key:string,callback:AsyncCallback<void>):void从实例中删除指定key的存储键值对
flush(callback:AsyncCallback<void>):void把当前实例中的数据异步存储到用户首选项持久化文件中
on(type:'change',callback?:Callback<{key:string}>):void订阅数据变更,订阅的key的值发生变化,在执行flush方法后,触发callback回调
off(type:'change',callback?:Callback<{key:string}>):void取消订阅数据变更
deletePreferences(context:Context,name:string,callback:AsyncCallback<void>):void从内存中移除指定实例,如果这个实例有对应的持久化文件则同时会把持外化文件删除

3.4、开发步骤

1、导入用户首选项模块

import dataPreferences from '@ohos.data.preferences';

 2、获取Preferences实例,读取指定文件,把数据加载到Preferences实例,用于数据操作

  1. import UIAbility from '@ohos.app.ability.UIAbility';
  2. import hilog from '@ohos.hilog';
  3. import window from '@ohos.window';
  4. import dataPreferences from '@ohos.data.preferences';
  5. export default class EntryAbility extends UIAbility {
  6. onCreate(want, launchParam) {
  7. }
  8. onDestroy() {
  9. }
  10. onWindowStageCreate(windowStage: window.WindowStage) {
  11. // Main window is created, set main page for this ability
  12. try{
  13. dataPreferences.getPreferences(this.context,'mystore',(err,preferences) => {
  14. if(err) {
  15. console.error(`Failed to get preferences. Code:${err.code},Message:${err.message}`);
  16. return;
  17. }
  18. console.info('Succeeded in getting preferences.')
  19. // 进行相关的数据操作
  20. })
  21. } catch (err) {
  22. console.error(`Failed to get preferences. Code:${err.code},Message:${err.message}`);
  23. }
  24. windowStage.loadContent('pages/Index', (err, data) => {
  25. if (err.code) {
  26. hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
  27. return;
  28. }
  29. });
  30. }
  31. onWindowStageDestroy() {
  32. // Main window is destroyed, release UI related resources
  33. }
  34. onForeground() {
  35. // Ability has brought to foreground
  36. }
  37. onBackground() {
  38. // Ability has back to background
  39. }
  40. }

在onWindowStageCreate方法中进行读取

3、写入数据

使用put()方法保存数据到缓存的Preferences实例中,在写入数据后如果有必要可以使用flush()方法把Preferences实例的数据存储到持久化文件。

注意:如果键此时已存在则会修改值,如果需要是在键不存在时新增键值对,则需要使用has()进行检查

4、读取数据

使用get()方法获取数据,如果值为null或者非默认值类型,则返回默认数据。

5、删除数据

使用delete()方法删除指定的键值对

6、据的持久化

应用存入数据到Preferences后,可以使用flush()方法实现数据持久化

7、订阅数据更新

使用on(),订阅key值发生变化,flush()执行时,会回调其中的回调方法

8、删除指定文件

使用deletePreferences()方法从内存中移除指定文件对应的Preferences实例,包括内存中的数据。若该Preference存在对应的持久化文件,则同时删除该持久化文件,包括指定文件及其备份文件、损坏文件。

  1. // EntryAbility.ts
  2. import UIAbility from '@ohos.app.ability.UIAbility';
  3. import hilog from '@ohos.hilog';
  4. import window from '@ohos.window';
  5. import dataPreferences from '@ohos.data.preferences';
  6. export default class EntryAbility extends UIAbility {
  7. onCreate(want, launchParam) {
  8. }
  9. onDestroy() {
  10. }
  11. onWindowStageCreate(windowStage: window.WindowStage) {
  12. // Main window is created, set main page for this ability
  13. try{
  14. dataPreferences.getPreferences(this.context,'mystore',(err,preferences) => {
  15. if(err) {
  16. console.error(`Failed to get preferences. Code:${err.code},Message:${err.message}`);
  17. return;
  18. }
  19. console.info('Succeeded in getting preferences.')
  20. // 进行相关的数据操作
  21. globalThis.dataPreferences = preferences;
  22. })
  23. } catch (err) {
  24. console.error(`Failed to get preferences. Code:${err.code},Message:${err.message}`);
  25. }
  26. windowStage.loadContent('pages/Index', (err, data) => {
  27. if (err.code) {
  28. hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
  29. return;
  30. }
  31. });
  32. }
  33. onWindowStageDestroy() {
  34. // Main window is destroyed, release UI related resources
  35. }
  36. onForeground() {
  37. // Ability has brought to foreground
  38. }
  39. onBackground() {
  40. // Ability has back to background
  41. }
  42. }
  1. // index.ets
  2. import dataPreferences from '@ohos.data.preferences';
  3. import Prompt from '@system.prompt';
  4. import common from '@ohos.app.ability.common';
  5. @Entry
  6. @Component
  7. struct Index {
  8. @State message: string = '';
  9. @State message1: string = '';
  10. dpf:dataPreferences.Preferences = globalThis.dataPreferences;
  11. build() {
  12. Row() {
  13. Column() {
  14. Text(this.message)
  15. .fontSize(50)
  16. .fontWeight(FontWeight.Bold)
  17. .margin({bottom:10})
  18. Text(this.message1)
  19. .fontSize(50)
  20. .fontWeight(FontWeight.Bold)
  21. .margin({bottom:10})
  22. Button('put')
  23. .margin({bottom:15})
  24. .onClick(() => {
  25. try{
  26. this.dpf.has('startup', (err,val) => {
  27. if(err) {
  28. console.error(`Failed to check data. Code:${err.code}, message:${err.message}`);
  29. return;
  30. }
  31. if (val) {
  32. console.info('startup is exists!!')
  33. } else {
  34. try {
  35. this.dpf.put('startup', 'auto', (err) => {
  36. if (err) {
  37. console.error(`Failed to put data. Code:${err.code}, message:${err.message}`);
  38. return;
  39. }
  40. console.info('succeeded in putting data.')
  41. })
  42. } catch (err) {
  43. console.error(`Failed to put data. Code:${err.code}, message:${err.message}`);
  44. }
  45. }
  46. })
  47. }catch(err) {
  48. console.error(`Failed to put data. Code:${err.code}, message:${err.message}`);
  49. }
  50. })
  51. Button('get')
  52. .margin({bottom:15})
  53. .onClick(() => {
  54. try{
  55. this.dpf.get('startup','default',(err,val) => {
  56. if(err) {
  57. console.error(`Failed to get data. Code:${err.code}, message:${err.message}`);
  58. }
  59. console.info(`succeeded in getting value of 'startup'. val:${val} `);
  60. this.message = val.toString();
  61. })
  62. }catch (err) {
  63. console.error(`Failed to get data. Code:${err.code}, message:${err.message}`);
  64. }
  65. })
  66. Button('delete')
  67. .margin({bottom:15})
  68. .onClick(() => {
  69. try{
  70. this.dpf.delete('startup', (err) => {
  71. if(err) {
  72. console.error(`Failed to delete data. Code:${err.code}, message:${err.message}`);
  73. return;
  74. }
  75. console.info('succeeded in deleting the data')
  76. })
  77. } catch (err) {
  78. console.error(`Failed to delete data. Code:${err.code}, message:${err.message}`);
  79. }
  80. })
  81. Button('flush')
  82. .margin({bottom:15})
  83. .onClick(() => {
  84. try{
  85. this.dpf.flush((err) => {
  86. console.error(`Failed to flush data. Code:${err.code}, message:${err.message}`);
  87. return;
  88. })
  89. Prompt.showToast({
  90. message: '数据持久化成功!',
  91. })
  92. } catch (err) {
  93. console.error(`Failed to flush data. Code:${err.code}, message:${err.message}`);
  94. }
  95. })
  96. Button('订阅')
  97. .margin({bottom:15})
  98. .onClick(() => {
  99. this.dpf.on('change',(key) => {
  100. console.info(key + '数据发生变化')
  101. })
  102. })
  103. Button('更新')
  104. .margin({bottom:15})
  105. .onClick(() => {
  106. try{
  107. this.dpf.put('startup','manual',(err) => {
  108. if(err) {
  109. console.error(`Failed to put data. Code:${err.code}, message:${err.message}`);
  110. return;
  111. }
  112. })
  113. } catch (err){
  114. console.error(`Failed to put data. Code:${err.code}, message:${err.message}`);
  115. }
  116. })
  117. Button('deletePreferences')
  118. .onClick(() => {
  119. try{
  120. let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  121. dataPreferences.getPreferences(context,'mystore', (err, val) => {
  122. if(err) {
  123. console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`);
  124. return;
  125. }
  126. console.info(`successed to delete preferences.`);
  127. })
  128. } catch (err) {
  129. console.error(`Failed to delete preferences. Code:${err.code}, message:${err.message}`);
  130. }
  131. })
  132. }
  133. .width('100%')
  134. }
  135. .height('100%')
  136. }
  137. }

4、键值型数据库实现数据持久化

4.1、使用场景介绍

键值型数据库存储键值对形式的数据,一般用来存储的数据没有复杂的关系模型。

4.2、使用约束

1、设备协同数据库,针对每条记录,key的长度小于等于896Byte,value小于4MB

2、单版本数据库,针对每条记录,key的长度小于等于1KB,value小于4MB

3、每个应用程序最多支持同时打开16个键值型分布式数据库

4、键值型数据库事件回调方法不允许进行阻塞操作

4.3、相关接口说明

接口大部分是异步操作,异步接口都有callback和Promise两种形式

接口名称描述
createKVManager(config: KVManagerConfig): KVManager创建一个KVManager对象实例,用于管数据库对象
getKVStore<T>(storeId:string,options:Options,callback:AsyncCallback<T>):void指定Options和storeId,创建并得到指定类型的KVStore数据库
put(key:string,value:Uint8Array|string|number|boolean,callback:AsyncCallback<void>):void添加指定类型的键值对到数据库
get(key:string,callback:AsyncCallback<Uint8Array|string|number|boolean>):void 获取指定键对应的值
delete(key:string,callback:AsyncCallback<void>):void从数据库中删除指定键值数据

4.4、开发步骤

 1、获取一个KVManager实例

在EntryAbility.ts中onCreate()或onWindowStageCreate()中创建。

  1. onWindowStageCreate(windowStage: window.WindowStage) {
  2. // Main window is created, set main page for this ability
  3. // KVManagerConfig
  4. let context = this.context;
  5. const KvManagerConfig = {
  6. context: context,
  7. bundleName: 'com.xiaoxie'
  8. };
  9. try{
  10. let kvManager = distributedKVStore.createKVManager(KvManagerConfig);
  11. console.info('Succeeded in create KVManager.')
  12. globalThis.kvManager = kvManager;
  13. } catch (err){
  14. console.error(`Failed to create KVManager, Code:${err.code},Message:${err.Message}`);
  15. }
  16. windowStage.loadContent('pages/KVStore', (err, data) => {
  17. if (err.code) {
  18. hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? '');
  19. return;
  20. }
  21. });
  22. }

2、创建并获取键值数据库

3、调用put()方法向键值数据库中插入数据,当我们据时key值存在则会修改其值,否则新增一条数据

4、调用get()方法获取指定键值

5、调用delete()方法删除指定键值的数据

  1. // KVStore.ets
  2. import distributedKVStore from '@ohos.data.distributedKVStore';
  3. import Prompt from '@system.prompt';
  4. const options = {
  5. createIfMissing: true, // 当数据库文件不存在的时候是否创建,默认创建
  6. encrypt: false, // 设置数据库文件是否加密,默认不加密
  7. backup: false, // 设置数据库文件是否备份,默认备份
  8. kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, // 设置要创建数据库的类型,默认为多设备协同
  9. securityLevel: distributedKVStore.SecurityLevel.S2 // 设置数据库的安全级别
  10. };
  11. @Entry
  12. @Component
  13. struct KVStore {
  14. @State message: string = '';
  15. kvManager:distributedKVStore.KVManager = globalThis.kvManager
  16. kvStore:distributedKVStore.SingleKVStore = undefined;
  17. build() {
  18. Row() {
  19. Column() {
  20. Text(this.message)
  21. .fontSize(20)
  22. .fontWeight(FontWeight.Bold)
  23. .margin({bottom:10})
  24. Button('1、创建并获取键值数据库')
  25. .width('50%')
  26. .margin({bottom:10})
  27. .onClick(() => {
  28. try{
  29. this.kvManager.getKVStore('storeId',options,(err,kvStore:distributedKVStore.SingleKVStore) => {
  30. if(err) {
  31. console.error(`Failed to get KVStore, Code:${err.code},Message:${err.message}`);
  32. return;
  33. }
  34. Prompt.showToast({
  35. message: '获取键值数据库成功!',
  36. duration: 1500
  37. })
  38. this.kvStore = kvStore;
  39. });
  40. } catch (e) {
  41. console.error(`Failed to get KVStore, Code:${e.code},Message:${e.message}`);
  42. }
  43. })
  44. Button('2、向键值数据库插入数据')
  45. .width('50%')
  46. .margin({bottom: 10})
  47. .onClick(() => {
  48. try{
  49. if(this.kvStore) {
  50. this.kvStore.put('test_key','test_value',(err) => {
  51. if(err) {
  52. console.error(`Failed to put data, Code:${err.code},Message:${err.message}`);
  53. return;
  54. }
  55. Prompt.showToast({
  56. message: '向键值数据加中插入数据成功!',
  57. duration: 1500
  58. })
  59. })
  60. } else {
  61. Prompt.showToast({
  62. message: '错误:请先获取数据库!',
  63. duration: 1500
  64. })
  65. }
  66. } catch (e) {
  67. console.error(`Failed to put data, Code:${e.code},Message:${e.message}`);
  68. }
  69. })
  70. Button('3、获取指定键的值')
  71. .width('50%')
  72. .margin({bottom:10})
  73. .onClick(() => {
  74. try{
  75. if(this.kvStore) {
  76. this.kvStore.get('test_key',(err,data) => {
  77. if(err) {
  78. this.message = '';
  79. console.error(`Failed to get data, Code:${err.code},Message:${err.message}`);
  80. return;
  81. }
  82. this.message = '';
  83. this.message = data.toString();
  84. })
  85. } else {
  86. Prompt.showToast({
  87. message: '错误:请先获取数据库!',
  88. duration: 1500
  89. })
  90. }
  91. } catch (e) {
  92. console.error(`Failed to get data, Code:${e.code},Message:${e.message}`);
  93. }
  94. })
  95. Button('4、删除指定键值数据')
  96. .width('50%')
  97. .onClick(() => {
  98. try{
  99. if(this.kvStore) {
  100. this.kvStore.delete('test_key',(err) => {
  101. if(err) {
  102. console.error(`Failed to delete data, Code:${err.code},Message:${err.message}`);
  103. return;
  104. }
  105. Prompt.showToast({
  106. message: '删除指定键值数据成功!',
  107. duration: 1500
  108. })
  109. })
  110. } else {
  111. Prompt.showToast({
  112. message: '错误:请先获取数据库!',
  113. duration: 1500
  114. })
  115. }
  116. } catch (e){
  117. console.error(`Failed to delete data, Code:${e.code},Message:${e.message}`);
  118. }
  119. })
  120. }
  121. .width('100%')
  122. }
  123. .height('100%')
  124. }
  125. }

5、关系型数据库实现数据持久化

5.1、使用场景介绍

关系型数据库基于SQLite组件,适用于存储包含复杂关系数据的场景。

5.2、相关术语介绍

1、谓词:数据库中用来代表数据实体的性质、特征或数据实体之间关系的词项,它主要用来定义数据库的操作条件。

2、结果集:指的是用户查询后的结果集合。

5.3、动作机制

关系型数据库对应用提供通用的操作接口,底层使用SQLite作为持久化存储引擎。

5.4、约束限制

1、系统默认日志方式是WAL(Write Ahead Log)模式,默认落盘方式是FULL模式

2、连接池最大个数是4个

3、数据库同一时间只能支持一个写操作

4、当应用被卸载完成后,设备上的相关数据库文件及临时文件会被自动清除

5.5、相关接口说明

大部分为异步接口,异步接口都有callback和Promise两种形式

接口说明描述
getRdbStore(context: Context, config: StoreConfig, callback:AsyncCallback<RdbStore>): void获得一个RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口来执行相关的数据操作
executeSql(sql: string, bindArgs:Array<ValueType>,callback:AsyncCallback<void>): void执行包含指定参数但是不返回值的sql语句
inser(table:string,values:valuesBucket,callback:AsyncCallback<number>): void向表中插入一行数据
update(values:ValuesBucket,predicates:RdbPredicates,callback:AsyncCallback<number>): void根据RdbPredicates的指定实例对象更新数据库中数据
delete(predicates:RdbPredicates,callback:AsyncCallback<number>):void根据RdbPredicates的指定实例对象删除数据库中数据
query(predicates:RdbPredicates,columns:Array<string>,callback:AsyncCallback<ResultSet>):void根据指定条件查询数据库中的数据
deleteRdbStore(context:Context,name:string,callback:AsyncCallback<void>):void删除数据库

5.6、开发步骤

 1、获取一个RdbStore

在EntryAbility.ts文件件的onCreate()或onWindowStageCreate()方法中创建数据库获取到RdbStore对象并绑定到globalThis,便于后续使用。

  1. // EntryAbility.ts
  2. onWindowStageCreate(windowStage: window.WindowStage) {
  3. // RdbStore
  4. const STORE_CONFIG = {
  5. name: 'RdbTest.db', // 数据库名称
  6. securityLevel: relationalStore.SecurityLevel.S1 // 数据库的安全级别
  7. };
  8. relationalStore.getRdbStore(this.context, STORE_CONFIG, (err,store) => {
  9. if(err) {
  10. console.error(`Failed to create rdbstore. Code:${err.code},Message:${err.message}`);
  11. return;
  12. }
  13. console.info('Succeeded in create RdbStore.')
  14. globalThis.rdbStore = store;
  15. })
  16. }

2、创建数据表,定义好建表语句,执行executeSql()方法

3、调用insert()方法来插入数据

注意:关系型数据库没有显式的flush操作实现持久化,数据插入即保存在持久化文件

4、根据谓词指定的实例对象,对数据进行修改或删除

5、根据谓词指定的查询条件查找数据,调用query()方法查找数据,会返回一个ResultSet结果集,当应用完成查询数据操作,不再使用ResultSet时,及时调用close方法关闭结查集,释放内存空间。

5、删除数据库,调用deleteRdbStore()方法,用来删除数据库及数据库相关的文件

  1. import relationalStore from '@ohos.data.relationalStore'
  2. import Prompt from '@system.prompt';
  3. import common from '@ohos.app.ability.common';
  4. @Entry
  5. @Component
  6. struct RdbStore {
  7. @State message: string = ''
  8. rdbStore: relationalStore.RdbStore = globalThis.rdbStore;
  9. build() {
  10. Row() {
  11. Column() {
  12. Text(this.message)
  13. .fontSize(20)
  14. .fontWeight(FontWeight.Bold)
  15. .margin({bottom:10})
  16. Button('创建数据表')
  17. .width('50%')
  18. .margin({bottom:10})
  19. .onClick(() => {
  20. try {
  21. // 数据库建表语句
  22. let SQL_CREATE_TABLE: string = 'create table if not exists employee(id integer primary key autoincrement, name text not null, age integer, salary real, codes blob)';
  23. this.rdbStore.executeSql(SQL_CREATE_TABLE); // 执行sql语句,创建数据表
  24. Prompt.showToast({
  25. message: '创建数据表成功',
  26. duration: 1500
  27. })
  28. } catch (err) {
  29. console.error(`创建数据表失败,Code:${err.code},Message:${err.Message}`);
  30. }
  31. })
  32. Button('向数据表中插入数据')
  33. .width('50%')
  34. .margin({bottom:10})
  35. .onClick(() => {
  36. let valueBucket = {
  37. 'name': '张三',
  38. 'age': 18,
  39. 'salary': 20000.00,
  40. 'codes' : new Uint8Array([1,2,3,4,5])
  41. };
  42. this.rdbStore.insert('employee',valueBucket,(err,rowId) => {
  43. if(err) {
  44. console.error(`Failed to insert data. Code:${err.code},Message:${err.message}}`);
  45. return;
  46. }
  47. Prompt.showToast({
  48. message: `插入数据成功,插入数据id:${rowId}`,
  49. duration: 2000
  50. })
  51. })
  52. })
  53. Button('修改数据表中指定数据')
  54. .width('50%')
  55. .margin({bottom:10})
  56. .onClick(() => {
  57. let valueBucket = {
  58. 'name': '李四',
  59. 'age': 18,
  60. 'salary': 20000.00,
  61. 'codes' : new Uint8Array([1,2,3,4,5])
  62. };
  63. let predicates = new relationalStore.RdbPredicates('employee'); // 创建表employee的predicates
  64. predicates.equalTo('name','张三'); // 匹配employee中name为张三的字段
  65. this.rdbStore.update(valueBucket,predicates,(err,rows) => {
  66. if(err) {
  67. console.error(`Failed to update data. Code:${err.code},Message:${err.message}}`);
  68. return;
  69. }
  70. Prompt.showToast({
  71. message: `修改数据成功,修改影响记录行数:${rows}`,
  72. duration: 2000
  73. })
  74. })
  75. })
  76. Button('删除数据表中指定数据')
  77. .width('50%')
  78. .margin({bottom:10})
  79. .onClick(() => {
  80. let predicates = new relationalStore.RdbPredicates('employee');
  81. predicates.equalTo('name','李四');
  82. this.rdbStore.delete(predicates, (err,rows) => {
  83. if(err) {
  84. console.error(`Failed to delete data. Code:${err.code},Message:${err.message}}`);
  85. return;
  86. }
  87. Prompt.showToast({
  88. message: `删除数据成功,删除影响记录行数:${rows}`,
  89. duration: 2000
  90. })
  91. })
  92. })
  93. Button('查询数据')
  94. .width('50%')
  95. .margin({bottom:10})
  96. .onClick(() => {
  97. this.message = '';
  98. let predicates = new relationalStore.RdbPredicates('employee');
  99. predicates.equalTo('name','张三');
  100. this.rdbStore.query(predicates,['id','name','age','salary','codes'],(err,resultSet) => {
  101. if(err) {
  102. this.message = '';
  103. console.error(`Failed to query data. Code:${err.code}, message:${err.message}`);
  104. return;
  105. }
  106. // this.message = resultSet.columnNames.join('|')
  107. if(resultSet.rowCount > 0 ){
  108. resultSet.goToFirstRow();
  109. this.message = resultSet.getString(resultSet.getColumnIndex('name')) + ' - ' + resultSet.getDouble(resultSet.getColumnIndex('salary'));
  110. }
  111. resultSet.close();
  112. })
  113. })
  114. Button('删除数据库及相关文件')
  115. .width('50%')
  116. .onClick(() => {
  117. let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
  118. relationalStore.deleteRdbStore(context,'RdbTest.db',(err) => {
  119. if(err) {
  120. console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`);
  121. return;
  122. }
  123. Prompt.showToast({
  124. message: '删除数据库成功!',
  125. duration: 1500
  126. })
  127. })
  128. })
  129. }
  130. .width('100%')
  131. }
  132. .height('100%')
  133. }
  134. }

6、数据可靠性与安全性

6.1、功能场景说明

在系统运行中,存储损坏、存储空间不足、文件系统权限、系统掉电等等都可能导致数据库发生故障。为此数据管理提供了数据可靠与安全性相关的解决方案和保障。

  • 备份、恢复功能:重要业务数据丢失出息严重异常场景,可以通过备份恢复数据库,保障数据不丢失
  • 数据库加密功能:当数据库中存储一些敏感信息时,可以对数据库进行加密,提高数据的安全性
  • 数据库分类分级:提供基于数据安全标签和设备安全等级进行访问控制的能力,保证数据安

另: 备份数据库存储在应用的沙箱中,当存储空间不足时,可以选择删除本地的数据库备份,释放空间。

6.2、基本概念

6.2.1、数据库备份与恢复

  • 数据库备份:对当前数据库的数据库文件进行完整备份,在做备份时不用关闭数据库,直接调用对应的备份接口就可以了
  • 数据库恢复:从指定的备份文件恢复到当前数据库文件。恢复完后,当前数据库数据保持与指定备份文件一致

6.2.2、数据库加密

加密是对整个数据库文件的加密,可以增强数据库的安全性,有效保护数据库内容

6.2.3、数据库分类分级

分布式数据管理对数据实施分类分级保护,提供基于数据安全标签以及设备安全等级的访问控制机制。数据安全标签和设备安全等级越高,加密措施和访问控制措施越严格,数据安全性越高。

6.3、运作机制

6.3.1、数据库备份与恢复机制

数据库在备份时,会把当前数据库备份在指定的文件件中,后续对数据库的操作不会影响备份的数据库文件,只有当恢复指定的数据库文件时,才会把备份的数据库文件件覆盖当前数据库,实现回滚。

键值型数据库备份路径:/data/service/el1(el2)/public/database/...{appId}/kvdb/backup/...{storeId}

关系型数据库备份路径:/data/app/el1(el2)/100/database/...{bundlename}/rdb

6.3.2、数据库加密机制

在数据库加密时,开发者无需传入密钥,只需要设置数据库加密的状态即可。系统会自动帮助开发者把数据库加密。使用huks通用密钥库系统。

6.4、相关约束限制

数据库加密密钥一年自动更换一次

键值型数据库最多可以备份5份

键值型数据库的自动备份需要在熄屏且充电的状态下进行

6.5、数据库备份与恢复

键值型数据库和关系型数据库都支持数据库的备份与恢复。同时键值型数据库还可以删除数据库备份,以释放本地存储空间。

6.5.1、键值型数据库的备份、恢复及删除

键值型数据库,通过backup接口实现数据库备份,通过restore接口实现数据库恢复,通过deletebackup接口删除数据库备份。

  1. import distributedKVStore from '@ohos.data.distributedKVStore';
  2. import Prompt from '@system.prompt';
  3. const options = {
  4. createIfMissing: true,
  5. encrypt: false,
  6. backup: false,
  7. kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
  8. securityLevel: distributedKVStore.SecurityLevel.S2
  9. };
  10. @Entry
  11. @Component
  12. struct KVStoreBack {
  13. @State message: string = '';
  14. kvManager: distributedKVStore.KVManager = globalThis.kvManager;
  15. kvStore: distributedKVStore.SingleKVStore;
  16. build() {
  17. Row() {
  18. Column() {
  19. Text(this.message)
  20. .fontSize(20)
  21. .fontWeight(FontWeight.Bold)
  22. .margin({bottom:10})
  23. Button('1.创建并获取键值数据库')
  24. .width('50%')
  25. .margin({bottom:10})
  26. .onClick(() => {
  27. let kvStorePromise = this.kvManager.getKVStore("myStore",options);
  28. kvStorePromise.then((store: distributedKVStore.SingleKVStore) => {
  29. this.kvStore = store;
  30. }).catch((err) => {
  31. console.error(`创建并获取键值数据库失败, 失败代码:${err.code}, 失败原因:${err.message}`);
  32. return;
  33. })
  34. })
  35. Button('2.键值数据库插入数据')
  36. .width('50%')
  37. .margin({bottom:10})
  38. .onClick(() => {
  39. try {
  40. this.kvStore.put('name', 'xiaoxie', (err) => {
  41. if (err) {
  42. console.error(`存储数据失败, 失败代码:${err.code}, 失败原因:${err.message}`);
  43. return;
  44. }
  45. Prompt.showToast({
  46. message: '存储数据成功!!',
  47. duration: 1500
  48. })
  49. this.message = 'xiaoxie'; // 添加数据成功把message赋值为写入的值
  50. })
  51. } catch (e) {
  52. console.error(`存储数据失败, 失败代码:${e.code}, 失败原因:${e.message}`);
  53. }
  54. })
  55. Button('3.备份数据')
  56. .width('50%')
  57. .margin({bottom:10})
  58. .onClick(() => {
  59. try{
  60. let file = 'bk001';
  61. this.kvStore.backup(file, (err) => {
  62. if(err) {
  63. console.error(`备份数据失败, 失败代码:${err.code}, 失败原因:${err.message}`);
  64. } else {
  65. Prompt.showToast({
  66. message: `备份数据成功,备份文件:${file}`,
  67. duration: 1500
  68. })
  69. }
  70. })
  71. } catch (e) {
  72. console.error(`备份数据失败, 失败代码:${e.code}, 失败原因:${e.message}`);
  73. }
  74. })
  75. Button('4.删除数据')
  76. .width('50%')
  77. .margin({bottom:10})
  78. .onClick(() => {
  79. try{
  80. this.kvStore.delete('name',(err) => {
  81. if(err) {
  82. console.error(`删除数据失败, 失败代码:${err.code}, 失败原因:${err.message}`);
  83. return;
  84. }
  85. Prompt.showToast({
  86. message: '删除数据成功!',
  87. duration: 1500
  88. })
  89. this.message = ''; // 删除数据成功后把message置空
  90. })
  91. } catch (e) {
  92. console.error(`删除数据失败, 失败代码:${e.code}, 失败原因:${e.message}`);
  93. }
  94. })
  95. Button('5.恢复数据')
  96. .width('50%')
  97. .margin({bottom:10})
  98. .onClick(() => {
  99. this.message = ''
  100. try{
  101. this.kvStore.restore('bk001',(err) => {
  102. if(err) {
  103. console.error(`删除数据失败, 失败代码:${err.code}, 失败原因:${err.message}`);
  104. } else {
  105. try{
  106. this.kvStore.get('name',(err,data) => {
  107. if(err) {
  108. console.error(`获取数据失败, 失败代码:${err.code}, 失败原因:${err.message}`);
  109. return;
  110. }
  111. this.message = data.toString(); // 恢复数据后把message的值赋为恢复后的值
  112. })
  113. } catch (e) {
  114. console.error(`获取数据失败, 失败代码:${err.code}, 失败原因:${err.message}`);
  115. }
  116. }
  117. })
  118. } catch (e) {
  119. console.error(`恢复数据失败, 失败代码:${e.code}, 失败原因:${e.message}`);
  120. }
  121. })
  122. Button('6、删除备份')
  123. .width('50%')
  124. .onClick(() => {
  125. let files = ['bk001'];
  126. try{
  127. this.kvStore.deleteBatch(files).then((data) => {
  128. Prompt.showToast({
  129. message: `删除备份成功,文件:${data[0]},结果:${data[1]}`,
  130. })
  131. }).catch((err) => {
  132. console.error(`删除备份失败, 失败代码:${err.code}, 失败原因:${err.message}`);
  133. })
  134. } catch (e) {
  135. console.error(`删除备份失败, 失败代码:${e.code}, 失败原因:${e.message}`);
  136. }
  137. })
  138. }
  139. .width('100%')
  140. }
  141. .height('100%')
  142. }
  143. }

6.5.2、关系型数据库备份与恢复

关系型数据库,通过backup接口实现数据库备份,通过restore接口实现数据库恢复。

  1. import relationalStore from '@ohos.data.relationalStore';
  2. import Prompt from '@system.prompt';
  3. const SQL_CREATE_TABLE: string = 'create table if not exists employee(id integer primary key autoincrement, name text not null, age integer, salary real, codes blob)';
  4. @Entry
  5. @Component
  6. struct RdbStroeBack {
  7. @State message: string = '';
  8. rdbStore: relationalStore.RdbStore = globalThis.rdbStore;
  9. build() {
  10. Row() {
  11. Column() {
  12. Text(this.message)
  13. .fontSize(20)
  14. .fontWeight(FontWeight.Bold)
  15. .margin({bottom:10})
  16. Button('1.创建数据表')
  17. .width('50%')
  18. .margin({bottom:10})
  19. .onClick(() => {
  20. try{
  21. this.rdbStore.executeSql(SQL_CREATE_TABLE);
  22. Prompt.showToast({
  23. message:'创建数据表成功',
  24. duration:1500
  25. })
  26. } catch (e){
  27. console.error(`创建数据表失败!Code:${e.code},Message:${e.message}`);
  28. }
  29. })
  30. Button('2.向数据表插入数据')
  31. .margin({bottom:10})
  32. .width('50%')
  33. .onClick(() => {
  34. let valueBucket = {
  35. 'name': '赵子龙',
  36. 'age': 20,
  37. 'salary': 100.5,
  38. 'codes': new Uint8Array([1,2,3,4,5])
  39. };
  40. this.rdbStore.insert('employee',valueBucket).then((rowId) => {
  41. Prompt.showToast({
  42. message: '插入数据成功!',
  43. duration: 1500
  44. })
  45. this.message = `${rowId} - ${valueBucket.name} - ${valueBucket.salary}`
  46. }).catch((err) => {
  47. console.error(`插入数据失败!Code:${err.code},Message:${err.message}`);
  48. })
  49. })
  50. Button('3.备份数据库')
  51. .margin({bottom:10})
  52. .width('50%')
  53. .onClick(() => {
  54. this.rdbStore.backup('dbBackup.db',(err) => {
  55. if(err) {
  56. console.error(`备份数据库失败!Code:${err.code},Message:${err.message}`);
  57. return;
  58. }
  59. Prompt.showToast({
  60. message: '备份数据库成功!',
  61. duration: 1500
  62. })
  63. })
  64. })
  65. Button('4.删除数据')
  66. .width('50%')
  67. .margin({bottom:10})
  68. .onClick(() => {
  69. let predicates = new relationalStore.RdbPredicates('employee');
  70. predicates.equalTo('name','赵子龙');
  71. this.rdbStore.delete(predicates).then((rows) => {
  72. if(rows > 0) {
  73. this.message = ''; // 删除后清空界面展示信息
  74. }
  75. }).catch((e) => {
  76. console.error(`删除指定数据失败!Code:${e.code},Message:${e.message}`);
  77. })
  78. })
  79. Button('5.恢复数据')
  80. .width('50%')
  81. .onClick(() => {
  82. this.rdbStore.restore('dbBackup.db',(err) => {
  83. if(err) {
  84. console.error(`恢复数据失败. Code:${err.code},message:${err.message}`);
  85. } else {
  86. let predicates = new relationalStore.RdbPredicates('employee');
  87. predicates.equalTo('name','赵子龙');
  88. this.rdbStore.query(predicates,['id','name','salary'],(err,resultSet) => {
  89. if(err) {
  90. console.error(`查询数据失败. Code:${err.code},message:${err.message}`);
  91. } else {
  92. if(resultSet.rowCount > 0) {
  93. resultSet.goToFirstRow();
  94. this.message = resultSet.getLong(resultSet.getColumnIndex('id')) + ' - '
  95. + resultSet.getString(resultSet.getColumnIndex('name')) + ' - '
  96. + resultSet.getDouble(resultSet.getColumnIndex('salary'));
  97. }
  98. }
  99. })
  100. }
  101. })
  102. })
  103. }
  104. .width('100%')
  105. }
  106. .height('100%')
  107. }
  108. }

6.6、数据库加密

6.6.1、使用场景

为了增强数据库的安全性,数据库提供了一个安全适用的数据库加密能力,从而对数据库存储的内容实施有效保护。通过数据库加密等安全方法实现了数据库数据存储的保密性和完整性要求,使得数据库以密文方式存储并在密态方式下工作,确保了数据安全。

注意:加密后的数据库只能通过接口进行访问,无法通过其它的方式来打开数据库文件。数据库加密的属性在创建数据库时确认,无法变更。

键值型数据库和关系型数据库都直接数据加密操作

6.6.2、键值型数据库加密

通过options中encrypt参数来控制是否加密,默认是false,表示不加密,当这个参数为true时则表示加密处理。

  1. import distributedKVStore from '@ohos.data.distributedKVStore'
  2. import Prompt from '@system.prompt';
  3. const options = {
  4. createIfMissing: true,
  5. encrypt: true, // 数据库加密
  6. backup: false,
  7. kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
  8. securityLevel: distributedKVStore.SecurityLevel.S2
  9. };
  10. @Entry
  11. @Component
  12. struct KVStoreEncrypt {
  13. @State message: string = ''
  14. kvManager:distributedKVStore.KVManager = globalThis.kvManager;
  15. kvStore: distributedKVStore.SingleKVStore;
  16. build() {
  17. Row() {
  18. Column() {
  19. Text(this.message)
  20. .fontSize(20)
  21. .fontWeight(FontWeight.Bold)
  22. .margin({bottom:10})
  23. Button('创建加密数据库')
  24. .width('50%')
  25. .margin({bottom:10})
  26. .onClick(() => {
  27. this.kvManager.getKVStore('ms1',options,(err,store:distributedKVStore.SingleKVStore) => {
  28. if(err) {
  29. console.error(`创建加密数据库失败!,代码:${err.code},原因:${err.message}`);
  30. return;
  31. }
  32. this.kvStore = store;
  33. Prompt.showToast({
  34. message: `创建加密数据库成功!`,
  35. duration: 2000
  36. })
  37. })
  38. })
  39. }
  40. .width('100%')
  41. }
  42. .height('100%')
  43. }
  44. }

其中kvManager对象还是在EntryAbility.ts的onCreate或onWindowStageCreate中创建的

  1. // KVManagerConfig
  2. let context = this.context;
  3. const KvManagerConfig = {
  4. context: context,
  5. bundleName: 'com.xiaoxie'
  6. };
  7. try{
  8. let kvManager = distributedKVStore.createKVManager(KvManagerConfig);
  9. console.info('Succeeded in create KVManager.')
  10. globalThis.kvManager = kvManager;
  11. } catch (err){
  12. console.error(`Failed to create KVManager, Code:${err.code},Message:${err.Message}`);
  13. }

6.6.3、关系型数据库加密

关系型数据库,过在创建relationalStore.RdbStore时给定的config参数中指定encrypt:true即可。

这个参数默认是false的

  1. // RdbStore
  2. const STORE_CONFIG = {
  3. name: 'RdbTest.db', // 数据库名称
  4. securityLevel: relationalStore.SecurityLevel.S1 // 数据库的安全级别
  5. };
  6. relationalStore.getRdbStore(this.context, STORE_CONFIG, (err,store) => {
  7. if(err) {
  8. console.error(`Failed to create rdbstore. Code:${err.code},Message:${err.message}`);
  9. return;
  10. }
  11. console.info('Succeeded in create RdbStore.')
  12. globalThis.rdbStore = store;
  13. })

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号