目录:
- 1、鸿蒙实现数据管理的三种方式
- 2、用户首选项
- 3、键值型数据管理
- 3.1、获取KVManager实例,用于管理数据库对象
- 3.2、创建并获取键值数据库
- 3.3、调用put()方法向键值数据库中插入数据
- 3.4、调用get()方法获取指定键的值
- 3.5、调用delete()方法删除指定键值的数据
- 4、关系型数据管理
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 = 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
//下面首选项的方法可以在这里面执行,页面栈创建时就初始化用户首选项,就可以直接在代码中使用了
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、关系型数据管理
待完善。。。