前面使用了首选项的存储方式,因此将其他的两种存储方式(键值型数据库和关系型数据库)也学习一下,简单记录一下,并进行封装,方便后续使用。
1、效果预览
2、使用条件
2.1 键值型数据库
键值型数据库实现数据持久化width=device-width,initial-scale=1.0http://test.openharmony.cn:7780/pages/v4.0/zh-cn/application-dev/database/data-persistence-by-kv-store.md/
- 设备协同数据库,针对每条记录,Key的长度≤896 Byte,Value的长度<4 MB。
-
单版本数据库,针对每条记录,Key的长度≤1 KB,Value的长度<4 MB。
-
每个应用程序最多支持同时打开16个键值型分布式数据库。
-
键值型数据库事件回调方法中不允许进行阻塞操作,例如修改UI组件。
2.2 关系型数据库
关系型数据库实现数据持久化width=device-width,initial-scale=1.0http://test.openharmony.cn:7780/pages/v4.0/zh-cn/application-dev/database/data-persistence-by-rdb-store.md/
- 系统默认日志方式是WAL(Write Ahead Log)模式,系统默认落盘方式是FULL模式。
-
数据库中连接池的最大数量是4个,用以管理用户的读操作。
-
为保证数据的准确性,数据库同一时间只能支持一个写操作。
-
当应用被卸载完成后,设备上的相关数据库文件及临时文件会被自动清除。
-
ArkTS侧支持的基本数据类型:number、string、二进制类型数据、boolean。
-
为保证插入并读取数据成功,建议一条数据不要超过2M。超出该大小,插入成功,读取失败。
3、核心API
3.1 键值型数据库
-
createKVManager(创建一个KVManager对象实例)
-
getKVStore(指定Options和storeId,创建并得到指定类型的KVStore数据库)
-
put(添加指定类型的键值对到数据库)
-
get(获取指定键的值)
-
delete(从数据库中删除指定键值的数据)
3.2 关系型数据库
-
getRdbStore(获得一个相关的RdbStore,操作关系型数据库)
-
executeSql(执行包含指定参数但不返回值的SQL语句)
-
deleteRdbStore(删除数据库)
-
insert(插入一行数据)
-
delete(从数据库中删除数据)
-
update(更新数据库中的数据)
-
query(根据指定条件查询数据库中的数据)
4、封装与调用
4.1 键值型数据库
4.1.1 封装
import distributedKVStore from '@ohos.data.distributedKVStore';const BUNDLE_NAME = "dbName_tengyu"let context = getContext(this)
// 数据库对象
let kvManager: distributedKVStore.KVManager | undefined = undefined;
// KVStore数据库
let kvStore: distributedKVStore.SingleKVStore | undefined = undefined;class DistributedUtil {constructor() {this.createKeyValueDB();}async getKvManager(bundleName?: string) {const kvStoreConfig: distributedKVStore.KVManagerConfig = {context: context,bundleName: bundleName || BUNDLE_NAME};try {kvManager = distributedKVStore.createKVManager(kvStoreConfig);}catch (err) {console.error(`error:${err}`)}}// 创建并得到指定类型的KVStore数据库async createKeyValueDB(op?: distributedKVStore.Options) {if (kvManager === undefined) {this.getKvManager();}try {const options: distributedKVStore.Options = {// 当数据库文件不存在时是否创建数据库,默认为truecreateIfMissing: true,// 设置数据库文件是否加密,默认为false,即不加密encrypt: false,// 设置数据库文件是否备份,默认为true,即备份backup: false,// 设置数据库文件是否自动同步。默认为false,即手动同步autoSync: true,// kvStoreType不填时,默认创建多设备协同数据库kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION,// 多设备协同数据库:kvStoreType: distributedKVStore.KVStoreType.DEVICE_COLLABORATION,securityLevel: distributedKVStore.SecurityLevel.S1};kvManager.getKVStore<distributedKVStore.SingleKVStore>('storeId', op || 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) {console.error(`An unexpected error occurred. Code:${e.code},message:${e.message}`);}return kvStore;}// 删除指定键值的数据async deleteStoreData(key: string) {if (!kvStore) {return;}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}`);}}// 向键值数据库中插入数据async putStoreData(key: string, value: any) {if (!key || !value) {return}if(!kvStore) {kvStore = await this.createKeyValueDB();}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}`);}}// 获取指定键的值async getStoreData(key: string) {if (!key) {return}if(!kvStore) {kvStore = await this.createKeyValueDB();}return new Promise((resolve, reject) => {try {kvStore.get(key, (err, data) => {if (err != undefined) {console.error(`Failed to get data. Code:${err.code},message:${err.message}`);reject(err)return;}resolve(data)});} catch (err) {reject(err)console.error('TAG', `Failed to get value, Cause: ${err}`)}});}
}export default new DistributedUtil();
4.1.2 调用
import distributedUtil from '../../utils/distributedStrong'// 向数据库新增数据
distributedUtil.putStoreData('test0011', JSON.stringify({name: 666,age: 32,date: '2023.06.26'
}))// 获取数据库中的数据
distributedUtil.getStoreData('test0011').then(res => {console.log('===获取数据库中的数据====', JSON.stringify(res))
})
4.2 关系型数据库
关系型数据库运作机制
4.2.1 封装
import relationalStore from '@ohos.data.relationalStore';const DB_NAME = "RelationStoreDB.db"let context = getContext(this)
let store: relationalStore.RdbStore | undefined = undefined;class RelationalUtil {async getRdbStoreConfig(dbName?: string, config?: relationalStore.StoreConfig) {const STORE_CONFIG: relationalStore.StoreConfig = config || {// 数据库文件名name: dbName || DB_NAME,// 数据库安全级别securityLevel: relationalStore.SecurityLevel.S1,// 可选参数,指定数据库是否加密,默认不加密encrypt: false,};return STORE_CONFIG;}// 创建并得到指定类型的KVStore数据库async createDatabaseTable(sqlCreateTable: string) {const STORE_CONFIG = await this.getRdbStoreConfig();relationalStore.getRdbStore(context, STORE_CONFIG, (err, rdbStore: relationalStore.RdbStore) => {if (err) {console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);return;}console.info('Succeeded in getting RdbStore.');// 当数据库创建时,数据库默认版本为0store = rdbStore;store.executeSql(sqlCreateTable); // 创建数据表})}// 删除数据库async deleteDB(dbName: string = DB_NAME) {relationalStore.deleteRdbStore(context, dbName, (err) => {if (err) {console.error(`Failed to delete RdbStore. Code:${err.code}, message:${err.message}`);return;}console.info('Succeeded in deleting RdbStore.');});}// 向数据库中插入数据async insertDatas(tableName: string, valueBucket) {if (store != undefined) {(store as relationalStore.RdbStore).insert(tableName, valueBucket, (err, rowId: number) => {if (err) {console.error(`Failed to insert data. Code:${err.code}, message:${err.message}`);return;}console.info(`Succeeded in inserting data. rowId:${rowId}`);})}}// 对数据进行修改async updateDatas(tableName: string, valueBucket, key, val) {let predicates = new relationalStore.RdbPredicates(tableName); // 创建表tableName的predicatespredicates.equalTo(key, val); // 匹配表tableName中key为val的字段if (store != undefined) {(store as relationalStore.RdbStore).update(valueBucket, predicates, (err, rowId: number) => {if (err) {console.error(`Failed to insert data. Code:${err.code}, message:${err.message}`);return;}console.info(`Succeeded in inserting data. rowId:${rowId}`);})}}//根据谓词指定的查询条件查找数据async getDatas(tableName: string, atomArr: Array<string>, key: string, val: string | number) {let predicates = new relationalStore.RdbPredicates(tableName);predicates.equalTo(key, val);if (store != undefined) {return new Promise((resolve, reject) => {(store as relationalStore.RdbStore).query(predicates, atomArr, (err, resultSet) => {if (err) {console.error(`Failed to query data. Code:${err.code}, message:${err.message}`);reject(err);return;}resolve(resultSet);console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);})})}}
}export default new RelationalUtil();
4.2.2 调用
import relationalUtil from '../../utils/relationalStrong';
import { ValuesBucket } from '@ohos.data.ValuesBucket';const DB_NAME = 'testDB'
const TABLE_NAME = 'table1'
// 建库建表
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)';
relationalUtil.createDatabaseTable(SQL_CREATE_TABLE, DB_NAME);// 删除数据库
relationalUtil.deleteDB(DB_NAME);// 新增数据
const valBucket: ValuesBucket = {'NAME': 111,'AGE': 222,'SALARY': 333,'CODES': 444,
};
relationalUtil.insertDatas(TABLE_NAME, valBucket);// 修改数据
relationalUtil.updateDatas(TABLE_NAME, valBucket, 'NAME', 'Test001Val');// 获取数据
relationalUtil.getDatas(TABLE_NAME, ['NAME', 'AGE', 'SALARY'], 'NAME', 'Test001Val');