鸿蒙实现数据管理

目录:

1、鸿蒙实现数据管理的三种方式

  • 用户首选项
  • 键值型数据管理
  • 关系型数据管理

2、用户首选项

typescript 复制代码
import dataPreferences from '@ohos.data.preferences';
import preferences from '@ohos.data.preferences';
import { Log } from './Log';
import { ValueType } from '@kit.ArkData';

/**
 * 用户首选项工具类
 */
export class PreferencesUtil {
  static mPreferences ?: dataPreferences.Preferences

  /**
   * 初始化
   * @param context
   */
  static init(context: Context) {
    try {
      dataPreferences.getPreferences(context, 'Looper_Sp', (err, preferences) => {
        if (err) {
          Log.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
          return;
        }
        PreferencesUtil.mPreferences = preferences
        Log.info('Succeeded in getting preferences.');
        // 进行相关数据操作
      })
    } catch (err) {
      Log.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
    }
  }

  /**
   * 写数据
   * @param isFlush 是否持久化
   */
  static writeData(key: string, value: ValueType, isFlush: boolean): Promise<boolean> {
    return new Promise((resolve, reject) => {
      try {
        PreferencesUtil.mPreferences?.put(key, value, (err) => {
          if (err) {
            Log.error(`Failed to put data. Code:${err.code}, message:${err.message}`);
            reject(false);
            return;
          }
          Log.info('Succeeded in putting data.');
          if (isFlush) {
            PreferencesUtil.flushData()
          }
          resolve(true);
        })
      } catch (err) {
        Log.error(`Failed to check the key 'startup'. Code:${err.code}, message:${err.message}`);
        reject(false);
      }
    });
  }

  /**
   * 读取数据
   */
  static readData<D>(key: string): Promise<D> {
    return new Promise((resolve, reject) => {
      if (PreferencesUtil.mPreferences == null) {
        reject(new Error("mPreferences is null"));
      } else {
        PreferencesUtil.mPreferences.get(key, "", (err, value) => {
          if (err) {
            reject(err);
            return;
          }
          resolve(value as D);
        })
      }
    });
  }

  /**
   * 删除数据
   * @param isFlush 是否持久化
   */
  static delData(key: string, isFlush: boolean): Promise<string> {
    return new Promise((resolve, reject) => {
      if (PreferencesUtil.mPreferences == null) {
        reject(new Error("mPreferences is null"));
      } else {
        PreferencesUtil.mPreferences.delete(key, (err, value) => {
          if (err) {
            reject(err);
            return;
          }
          if (isFlush) {
            PreferencesUtil.flushData()
          }
          resolve("删除成功");
        })
      }
    });
  }

  /**
   * 删除整个库
   * @param isFlush 是否持久化
   */
  static delDB(context: Context, storeName: string): Promise<string> {
    return new Promise((resolve, reject) => {
      dataPreferences.deletePreferences(context, storeName, (err, value) => {
        if (err) {
          reject(err);
          return;
        }
        resolve("删除成功");
      })
    });
  }

  /**
   * 持久化
   */
  static flushData() {
    if (PreferencesUtil.mPreferences != null) {
      try {
        PreferencesUtil.mPreferences.flush((err) => {
          if (err) {
            Log.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
            return;
          }
          Log.info('Succeeded in flushing.');
        })
      } catch (err) {
        Log.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
      }
    }
  }
}

let preferencesUtil = new PreferencesUtil()

export default preferencesUtil as PreferencesUtil
typescript 复制代码
//下面首选项的方法可以在这里面执行,页面栈创建时就初始化用户首选项,就可以直接在代码中使用了
onWindowStageCreate(ability, windowStage) {
PreferencesUtil.init(this.context)
console.info(TAG, "onWindowStageCreate ability:" + JSON.stringify(ability));
console.info(TAG, "onWindowStageCreate windowStage:" + JSON.stringify(windowStage));
}
//sp储存初始化
PreferencesUtil.init(this.context)
//写入信息
PreferencesUtil.writeData("zzz", "bbb", true)
//读取信息
PreferencesUtil.readData<string>("zzz").then(res => {
      Log.info("读取数据:" + res)
    })

3、键值型数据管理

3.1、获取KVManager实例,用于管理数据库对象

typescript 复制代码
// 导入模块
import { distributedKVStore } from '@kit.ArkData';
 
// Stage模型
import { window } from '@kit.ArkUI';
import { UIAbility } from '@kit.AbilityKit';
import { BusinessError } from '@kit.BasicServicesKit';
 
let kvManager: distributedKVStore.KVManager | undefined = undefined;
 
export default class EntryAbility extends UIAbility {
  onCreate() {
    let context = this.context;
    const kvManagerConfig: distributedKVStore.KVManagerConfig = {
      context: context,
      bundleName: 'com.example.datamanagertest'
    };
    try {
      // 创建KVManager实例
      kvManager = distributedKVStore.createKVManager(kvManagerConfig);
      console.info('Succeeded in creating KVManager.');
      // 继续创建获取数据库
    } catch (e) {
      let error = e as BusinessError;
      console.error(`Failed to create KVManager. Code:${error.code},message:${error.message}`);
    }
  }
}
if (kvManager !== undefined) {
   kvManager = kvManager as distributedKVStore.KVManager;
  //进行后续操作
  //...
}

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

typescript 复制代码
let kvStore: distributedKVStore.SingleKVStore | undefined = undefined;
try {
  const options: distributedKVStore.Options = {
    createIfMissing: true,
    encrypt: false,
    backup: false,
    autoSync: false,
    // kvStoreType不填时,默认创建多设备协同数据库
    kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,
    // 多设备协同数据库:kvStoreType: distributedKVStore.KVStoreType.DEVICE_COLLABORATION,
    securityLevel: distributedKVStore.SecurityLevel.S1
  };
  kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', options, (err, store: distributedKVStore.SingleKVStore) => {
    if (err) {
      console.error(`Failed to get KVStore: Code:${err.code},message:${err.message}`);
      return;
    }
    console.info('Succeeded in getting KVStore.');
    kvStore = store;
    // 请确保获取到键值数据库实例后,再进行相关数据操作
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
}
if (kvStore !== undefined) {
  kvStore = kvStore as distributedKVStore.SingleKVStore;
    //进行后续操作
    //...
}

3.3、调用put()方法向键值数据库中插入数据

typescript 复制代码
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value_test_string';
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
    if (err !== undefined) {
      console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
      return;
    }
    console.info('Succeeded in putting data.');
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
}

说明:

当Key值存在时,put()方法会修改其值,否则新增一条数据。

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

typescript 复制代码
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
    if (err !== undefined) {
      console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
      return;
    }
    console.info('Succeeded in putting data.');
    kvStore = kvStore as distributedKVStore.SingleKVStore;
    kvStore.get(KEY_TEST_STRING_ELEMENT, (err, data) => {
      if (err != undefined) {
        console.error(`Failed to get data. Code:${err.code},message:${err.message}`);
        return;
      }
      console.info(`Succeeded in getting data. Data:${data}`);
    });
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`Failed to get data. Code:${error.code},message:${error.message}`);
}

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

typescript 复制代码
try {
  kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, (err) => {
    if (err !== undefined) {
      console.error(`Failed to put data. Code:${err.code},message:${err.message}`);
      return;
    }
    console.info('Succeeded in putting data.');
    kvStore = kvStore as distributedKVStore.SingleKVStore;
    kvStore.delete(KEY_TEST_STRING_ELEMENT, (err) => {
      if (err !== undefined) {
        console.error(`Failed to delete data. Code:${err.code},message:${err.message}`);
        return;
      }
      console.info('Succeeded in deleting data.');
    });
  });
} catch (e) {
  let error = e as BusinessError;
  console.error(`An unexpected error occurred. Code:${error.code},message:${error.message}`);
}

4、关系型数据管理

待完善。。。

相关推荐
ChinaDragonDreamer39 分钟前
HarmonyOS:多线程并发-Worker
harmonyos·鸿蒙
吴冰_hogan2 小时前
MySQL索引优化
android·mysql
Qin_jiangshan6 小时前
使用HBuilderX 进行uniapp 打包Android APK
android·uni-app
crownyouyou6 小时前
华为平板与非华为电脑多屏协同及Bug处理
华为·电脑·bug
jzlhll1237 小时前
android编译assets集成某文件太大更新导致git仓库变大
android
Random_index8 小时前
#HarmonyOS篇: 学习资料
harmonyos
路-buan9 小时前
华为eNSP:VRRP的主备备份
网络·华为·智能路由器
文火冰糖的硅基工坊13 小时前
[创业之路-182]:《华为战略管理法-DSTE实战体系》-1-华为的发展历程和战略管理演变
华为·产品经理·需求分析·产品·创业·战略
马剑威(威哥爱编程)13 小时前
优雅的@ObservedV2和@Trace装饰器
harmonyos·arkts·鸿蒙·harmonyos-next
高林雨露13 小时前
ImageView android:scaleType各种属性
android·imageview各种属性