根据提供的资料,我们可以进一步扩展之前的博客文章,加入键值型数据库(KV-Store)和关系型数据库(RelationalStore)的内容。下面是整合后的完整博客草稿,包含了所有必要的代码示例:
HarmonyOS 应用数据持久化指南
引言
在HarmonyOS应用开发中,数据持久化是一项重要的功能。本文将介绍三种常见的数据持久化方式:用户首选项(Preferences)、键值型数据库(KV-Store)以及关系型数据库(RelationalStore),并给出相应的代码示例。
用户首选项(Preferences)
用户首选项是一种简单的数据持久化方式,适合存储少量配置信息。
示例代码
import dataPreferences from '@ohos.data.preferences';
// 获取Preferences实例
function getPreferences(context, storeName) {
try {
dataPreferences.getPreferences(context, storeName, (err, preferences) => {
if (err) {
console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
return;
}
console.info('Succeeded in getting preferences.');
// 进行相关数据操作
});
} catch (err) {
console.error(`Failed to get preferences. Code:${err.code},message:${err.message}`);
}
}
// 写入数据
function putData(preferences, key, value) {
try {
preferences.put(key, value, (err) => {
if (err) {
console.error(`Failed to put data. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in putting data.');
});
} catch (err) {
console.error(`Failed to put data. Code: ${err.code},message:${err.message}`);
}
}
// 读取数据
function getData(preferences, key, defaultValue) {
try {
preferences.get(key, defaultValue, (err, val) => {
if (err) {
console.error(`Failed to get value of '${key}'. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`Succeeded in getting value of '${key}'. val: ${val}.`);
});
} catch (err) {
console.error(`Failed to get value of '${key}'. Code:${err.code}, message:${err.message}`);
}
}
// 删除数据
function deleteData(preferences, key) {
try {
preferences.delete(key, (err) => {
if (err) {
console.error(`Failed to delete the key '${key}'. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`Succeeded in deleting the key '${key}'.`);
});
} catch (err) {
console.error(`Failed to delete the key '${key}'. Code:${err.code}, message:${err.message}`);
}
}
// 数据持久化
function flushData(preferences) {
try {
preferences.flush((err) => {
if (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
return;
}
console.info('Succeeded in flushing.');
});
} catch (err) {
console.error(`Failed to flush. Code:${err.code}, message:${err.message}`);
}
}
键值型数据库(KV-Store)
键值型数据库适用于存储无复杂关系的数据。
示例代码
import distributedKVStore from '@ohos.data.distributedKVStore';
// 获取KVManager实例
function createKVManager(context, bundleName) {
const kvManagerConfig = {
context: context,
bundleName: bundleName
};
try {
const kvManager = distributedKVStore.createKVManager(kvManagerConfig);
console.info('Succeeded in creating KVManager.');
return kvManager;
} catch (e) {
console.error(`Failed to create KVManager. Code:${e.code},message:${e.message}`);
return null;
}
}
// 创建并获取键值数据库
function getKVStore(kvManager, storeId, options) {
try {
kvManager.getKVStore(storeId, options, (err, kvStore) => {
if (err) {
console.error(`Failed to get KVStore. Code:${err.code},message:${err.message}`);
return;
}
console.info('Succeeded in getting KVStore.');
// 进行相关数据操作
});
} catch (e) {
console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
}
}
// 插入数据
function putData(kvStore, key, value) {
try {
kvStore.put(key, value, (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) {
console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
}
}
// 获取数据
function getData(kvStore, key) {
try {
kvStore.get(key, (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) {
console.error(`Failed to get data. Code:${e.code},message:${e.message}`);
}
}
// 删除数据
function deleteData(kvStore, key) {
try {
kvStore.delete(key, (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) {
console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);
}
}
关系型数据库(RelationalStore)
关系型数据库适用于存储具有复杂关系的数据。
示例代码
import relationalStore from '@ohos.data.relationalStore';
// 获取RdbStore
function getRdbStore(context, config) {
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)';
try {
relationalStore.getRdbStore(context, 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.executeSql(SQL_CREATE_TABLE); // 创建数据表
// 这里执行数据库的增、删、改、查等操作
});
} catch (e) {
console.error(`Failed to get RdbStore. Code:${e.code}, message:${e.message}`);
}
}
// 插入数据
function insertData(store, tableName, valueBucket) {
store.insert(tableName, valueBucket, (err, rowId) => {
if (err) {
console.error(`Failed to insert data. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`Succeeded in inserting data. rowId:${rowId}`);
});
}
// 更新数据
function updateData(store, valueBucket, tableName, name) {
let predicates = new relationalStore.RdbPredicates(tableName);
predicates.equalTo('NAME', name);
store.update(valueBucket, predicates, (err, rows) => {
if (err) {
console.error(`Failed to update data. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`Succeeded in updating data. row count: ${rows}`);
});
}
// 删除数据
function deleteData(store, tableName, name) {
let predicates = new relationalStore.RdbPredicates(tableName);
predicates.equalTo('NAME', name);
store.delete(predicates, (err, rows) => {
if (err) {
console.error(`Failed to delete data. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`Delete rows: ${rows}`);
});
}
// 查询数据
function queryData(store, tableName, name, columns) {
let predicates = new relationalStore.RdbPredicates(tableName);
predicates.equalTo('NAME', name);
store.query(predicates, columns, (err, resultSet) => {
if (err) {
console.error(`Failed to query data. Code:${err.code}, message:${err.message}`);
return;
}
console.info(`Succeeded in querying data.`);
while (resultSet.next()) {
console.log(`ID: ${resultSet.getInt('ID')}, Name: ${resultSet.getString('NAME')}, Age: ${resultSet.getInt('AGE')}, Salary: ${resultSet.getDouble('SALARY')}, Codes: ${resultSet.getBlob('CODES')}`);
}
resultSet.close();
});
}
结论
通过以上示例,您可以了解到如何在HarmonyOS应用中使用用户首选项(Preferences)、键值型数据库(KV-Store)以及关系型数据库(RelationalStore)进行数据持久化。选择合适的数据持久化方案对于提高应用的性能和用户体验至关重要。
这篇博客文章详细介绍了HarmonyOS应用中三种数据持久化方式的使用方法,并提供了完整的代码示例。希望这篇文章能够帮助您更好地理解和使用这些功能。