目录:
- 1、鸿蒙实现数据管理的三种方式
- 2、用户首选项
- 3、键值型数据管理
- 3.1、获取KVManager实例,用于管理数据库对象
- 3.2、创建并获取键值数据库
- 3.3、调用put()方法向键值数据库中插入数据
- 3.4、调用get()方法获取指定键的值
- 3.5、调用delete()方法删除指定键值的数据
- 4、关系型数据管理
- 4.1、导入模块
- 4.2、在abliity入口文件的生命周期函数onWindowStageCreat中添加初始化代码
- 4.3、RdbUtils工具类
- 4.4、创建数据库
- 4.5、插入数据
- 4.6、查询数据
- 4.7、修改和删除数据
- 4.8、删除数据库
1、鸿蒙实现数据管理的三种方式
- 用户首选项
- 键值型数据管理
- 关系型数据管理
2、用户首选项
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 = preferencesLog.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
//下面首选项的方法可以在这里面执行,页面栈创建时就初始化用户首选项,就可以直接在代码中使用了
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实例,用于管理数据库对象
// 导入模块
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、创建并获取键值数据库
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()方法向键值数据库中插入数据
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()方法获取指定键的值
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()方法删除指定键值的数据
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、关系型数据管理
4.1、导入模块
import relationalStore from '@ohos.data.relationalStore'; // 导入模块
4.2、在abliity入口文件的生命周期函数onWindowStageCreat中添加初始化代码
const STORE_CONFIG = {name: 'RdbTest.db', // 数据库文件名securityLevel: relationalStore.SecurityLevel.S1 // 数据库安全级别};relationalStore.getRdbStore(this.context, STORE_CONFIG, (err, store) => {if (err) {console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);return;}console.info(`Succeeded in getting RdbStore.`);//保存store, 方便后面我们对数据库的操作RdbUtils.setStore(store)});
4.3、RdbUtils工具类
import relationalStore from '@ohos.data.relationalStore';
export default class RdbUtils {private static rdbStore: relationalStore.RdbStore;static setStore(store: relationalStore.RdbStore) {RdbUtils.rdbStore = store;}static getStore(): relationalStore.RdbStore {return RdbUtils.rdbStore;}
}
4.4、创建数据库
import relationalStore from '@ohos.data.relationalStore';
export default class RdbUtils {...static executeSql(sql: string): Promise<void> {return RdbUtils.getStore().executeSql(sql);}...
}
示例:
import RdbUtils from '../common/rdbUtils/RdbUtils';
@Entry
@Component
struct Index {build() {Row() {Column() {Button('创建数据库表').onClick(() => {const SQL_CREATE_TABLE = 'CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)'; // 建表Sql语句RdbUtils.executeSql(SQL_CREATE_TABLE).then(() =>{openDialog('successfully created table')}).catch((err) => {openDialog(err);})})}.width('100%')}.height('100%')}
}function openDialog(text: string) {AlertDialog.show({title: 'title',message: text,autoCancel: true,alignment: DialogAlignment.Bottom,offset: { dx: 0, dy: -20 },})
}
4.5、插入数据
import relationalStore from '@ohos.data.relationalStore';
export default class RdbUtils {...static insert(tableName: string, data: any): Promise<number> {return RdbUtils.getStore().insert(tableName, data);}...
}
示例:
import RdbUtils from '../common/rdbUtils/RdbUtils';
@Entry
@Component
struct Index {build() {Row() {Column() {...Button('插入数据').onClick(() => {const valueBucket = {'NAME': 'Lisa','AGE': 18,'SALARY': 100.5,'CODES': new Uint8Array([1, 2, 3, 4, 5])};RdbUtils.insert('EMPLOYEE', valueBucket).then((updateNumber) => {openDialog('已插入数据:' + updateNumber)}).catch((error) => {openDialog('error: ' + error)})})...}.width('100%')}.height('100%')}
}
...
4.6、查询数据
static queryAll(): Promise<Array<Employee>> {let predicates = new relationalStore.RdbPredicates('EMPLOYEE');return new Promise<Array<Employee>>((resolve, reject) => {RdbUtils.getStore().query(predicates).then((result) => {let employees = new Array<Employee>();while (result.goToNextRow()) {let employee = new Employee(result.getLong(0),result.getString(1),result.getLong(2),result.getDouble(3),result.getBlob(4));employees.push(employee);}resolve(employees);}).catch((error) => {reject(error)})})}
该方法将通过RdbUtils.getStore().query(predicates)获取的结果集封装到Employee类中,然后通过Promise进行返回。
实体类Employee:
export default class Employee {id: number; // 员工IDname: string; // 姓名age: number | null; // 年龄,允许为nullsalary: number | null; // 工资,允许为nullcodes: Uint8Array | null; // 二进制数据,用于存储 BLOB 类型,允许为nullconstructor(id: number, name: string, age: number | null, salary: number | null, codes: Uint8Array | null) {this.id = id;this.name = name;this.age = age;this.salary = salary;this.codes = codes;}
}
示例:
import RdbUtils from '../common/rdbUtils/RdbUtils';
@Entry
@Component
struct Index {build() {Row() {Column() {...Button('查询数据').onClick(() => {RdbUtils.queryAll().then((employees: Array<Employee>) => {openDialog('employees: ' + JSON.stringify(employees))}).catch((error) => {openDialog('error' + error.toString())})})...}.width('100%')}.height('100%')}
}
...
4.7、修改和删除数据
在工具包中添加:
...static deleteById(id: number) {let predicates = new relationalStore.RdbPredicates('EMPLOYEE');predicates.equalTo('ID', id)return RdbUtils.getStore().delete(predicates);}static updateById(id: number, data: any) {let predicates = new relationalStore.RdbPredicates('EMPLOYEE');predicates.equalTo('ID', id)return RdbUtils.getStore().update(data, predicates);}
...
Button('修改数据').onClick(() => {const valueBucket = {'NAME': 'Rose','AGE': 999,'SALARY': 100.5,'CODES': new Uint8Array([1, 2, 3, 4, 5])};RdbUtils.updateById(1, valueBucket).then((updateNumber) => {openDialog('已更新数据:' + updateNumber.toString())}).catch((err) => {openDialog(err)})})Button('删除数据').onClick(() => {RdbUtils.deleteById(1).then((updateNumber) => {openDialog('已删除数据:' + updateNumber.toString())}).catch((err) => {openDialog(err)})})
4.8、删除数据库
export default class EntryAbility extends UIAbility {...onDestroy() {hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onDestroy');relationalStore.deleteRdbStore(this.context, 'RdbTest.db', (err) => {if (err) {console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`);return;}console.info('Succeeded in deleting RdbStore.');});}....
}
这里我在EntryAbility中的onDestroy生命周期函数中调用了删除数据库的操作,这意味着当我们的Ability被销毁的时候,自动将数据库删除。