HarmonyOS 鸿蒙Next数据持久化之关系型数据库
HarmonyOS 鸿蒙Next数据持久化之关系型数据库
指南:
- https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/data-persistence-by-rdb-store
- 关系型数据库备份: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/data-backup-and-restore# 关系型数据库备份
- 关系型数据库异常重建: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/data-backup-and-restore# 关系型数据库异常重建
- 关系型数据库数据恢复: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/data-backup-and-restore# 关系型数据库数据恢复
封装工具:
class dBUtils {
private rdbStore: relationalStore.RdbStore | null = null
/**
* 初始化数据库
* @param context 上下文对象
* @param tableName 创建的表格名字
*/
initDB(context: Context, tableName: string) {
// (1) 初始化数据库配置
const STORE_CONFIG: relationalStore.StoreConfig = {
name: 'xxx.db', // 数据库文件名
securityLevel: relationalStore.SecurityLevel.S1, // 数据库安全级别
}
// (2) 定义sql语句
const SQL_CREATE_TABLE = `CREATE TABLE IF NOT EXISTS ${tableName} (
ID INTEGER PRIMARY KEY AUTOINCREMENT,
NAME TEXT NOT NULL,
BIG_LOGO TEXT,
CODE TEXT,
PRICE REAL,
COUNT INTEGER,
CHECKED INTEGER)`
// (3) 初始化数据库(getRdbStore异步)
relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
if (err) {
console.log(`获取RdbStore失败,Code:${err.code},message:${err.message}`)
return
} else {
console.log(`获取RdbStore成功`);
this.rdbStore = store
// 有了数据库,就可以创建表格
store.executeSql(SQL_CREATE_TABLE, (error) => {
if (!error) {
console.log(`${tableName}创建成功`);
} else {
console.log('创建失败')
return
}
})
}
})
}
/**
* 添加数据到数据库
* @param tableName
* @value 要添加的数据
*/
insertDataDB(tableName: string, value: relationalStore.ValuesBucket) {
if (this.rdbStore !== null) {
this.rdbStore.insert(tableName, value, (err: BusinessError, rowId: number) => {
if (err) {
console.log(`往${tableName}中添加数据失败,${err.name}---${err.code}---${err.message}`)
return
}
console.log(`往${tableName}中添加数据成功,rowId:${rowId}`)
})
}
}
/**
*
* @param column 投影列['ID','NAME']
* @param tableName
*/
async queryDataDB(column: Array<string>, tableName: string, id?: number) {
// 获取要操作的对象
let predicates = new relationalStore.RdbPredicates(tableName)
// 筛选条件
if (id) {
predicates.equalTo('ID', id)
}
// 查询到的所有对象
let carts: CartModel[] = []
// 查询数据得到一个结果集,需要想办法将结果集转化为CartModel
const resultSet = await (this.rdbStore as relationalStore.RdbStore).query(predicates, column)
// goToNextRow判断结果集是否往下指向下一个数据
// ORM:对象和数据库进行数据转换
while (resultSet.goToNextRow()) {
// getColumnIndex找到数据库中指定某一行的列明
// getString 指定列的值获取到
let id = resultSet.getLong(resultSet.getColumnIndex('ID'))
let name = resultSet.getString(resultSet.getColumnIndex('NAME'))
let big_log = resultSet.getString(resultSet.getColumnIndex('BIG_LOG'))
let code = resultSet.getString(resultSet.getColumnIndex('CODE'))
let price = resultSet.getDouble(resultSet.getColumnIndex('PRICE'))
let count = resultSet.getLong(resultSet.getColumnIndex('COUNT'))
let checked = resultSet.getLong(resultSet.getColumnIndex('CHECKED'))
const temp: CartModel = new CartModel()
temp.id = id
temp.name = name
temp.big_logo = big_log
temp.code = code
temp.price = price
temp.count = count
temp.checked = checked
carts.push(temp)
}
resultSet.close()
return carts
}
/**
*删除指定的数据,购物车移出
* @param tableName
* @param id
*/
deleteById(tableName: string, id: number) {
// 获取要操作的对象
let predicates = new relationalStore.RdbPredicates(tableName)
// 筛选条件
predicates.equalTo('ID', id)
if (this.rdbStore !== null) {
this.rdbStore.delete(predicates, (err: BusinessError, rows: number) => {
if (err) {
console.log(`Failed to delete data . Code:${err.code},message:${err.message}`)
return
} else {
console.log(`Delete rows:${rows}`)
}
})
}
}
/**
*
* @param tableName 表名
* @param id 修改商品编号
* @param value 修改字段
* return rows 影响行
*/
updateById(tableName: string, id: number, value: relationalStore.ValuesBucket) {
// 获取要操作的对象
let predicates = new relationalStore.RdbPredicates(tableName)
// 筛选条件
predicates.equalTo('ID', id)
if (this.rdbStore !== null) {
this.rdbStore.update(value, predicates, (err: BusinessError, rows: number) => {
if (err) {
console.log(`Failed to delete data . Code:${err.code},message:${err.message}`)
return
} else {
console.log(`Delete rows:${rows}`)
}
})
}
}
}
const dBUtils = new dBUtils()
export { dBUtils }
Abiltuty中
onWindowStageCreate(windowStage: window.WindowStage): void {
// 加载在数据库
cartDBUtils.initDB(this.context,'tableName')
}
页面中使用
// insert
addCart=()=>{
// 构造一个数据结构
const valueBucket:relationalStore.ValuesBucket={
NAME:this.detail.name,
BIG_LOGO:this.detail.big_logo,
CODE:this.detail.id,
PRICE:Number(this.detail.price),
COUNT:1,
CHECKED:0
}
// 调用数据库,保存数据
dBUtils.insertDataDB('tableName',valueBucket)
}
//query
fetchDBData=async ()=>{
const res= await dBUtils.queryDataDB(
['ID','NAME','BIG_LOGO','PRICE','COUNT','CHECKED'],
'tableName'
)
this.carts=res
}
aboutToAppear(): void {
this.fetchDBData()
}
// update
const updateColumn:relationalStore.ValuesBucket={
COUNT:(this.item.goods_count as number)
}
dBUtils.updateById('tableName',Number(this.item.id),updateColumn)
更多关于HarmonyOS 鸿蒙Next数据持久化之关系型数据库的实战教程也可以访问 https://www.itying.com/category-93-b0.html
2 回复
HarmonyOS鸿蒙Next的关系型数据库基于SQLite实现,支持本地数据存储和高效查询。开发者可通过DataAbility
或RdbStore
接口进行数据操作,包括创建表、增删改查等。数据库支持事务处理,确保数据一致性。通过Predicates
类可构建复杂查询条件。数据加密功能可保护敏感信息。关系型数据库适用于结构化数据存储,如用户信息、配置数据等。
更多关于HarmonyOS 鸿蒙Next数据持久化之关系型数据库的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
从代码来看,这是一个典型的HarmonyOS Next关系型数据库(RDB)封装实现。主要特点如下:
- 数据库初始化:
- 使用getRdbStore异步创建数据库实例
- 配置了数据库名称和安全级别(S1)
- 通过executeSql执行建表SQL
- CRUD操作封装:
- 插入数据:insert方法配合ValuesBucket
- 查询数据:使用RdbPredicates构建查询条件,通过ResultSet遍历结果
- 更新和删除:同样基于RdbPredicates定位记录
- 类型安全:
- 使用了TypeScript类型定义
- 查询结果映射到CartModel实体类
- 异步处理:
- 查询使用async/await
- 其他操作使用回调函数处理结果
需要注意的几个问题:
- 代码中BIG_LOGO字段在创建表时写的是BIG_LOGO,但查询时变成了BIG_LOG
- 表字段COUNT在创建时缺少逗号分隔
- 错误处理可以更完善,比如加入Promise reject处理
这个封装基本覆盖了RDB的主要操作,可以作为项目中的数据库工具类使用。对于更复杂的场景,可能需要添加事务支持、批量操作等功能。