Harmony os Next——關系型數據庫relationalStore.RdbStore的使用
- 描述
- 數據庫的使用
- 建表
- 定義表信息
- 創建數據庫表
- 創建數據庫操作對象
- 增
- 更新
- 查詢
- 刪
- 數據庫的初始化
描述
本文通過存儲一個簡單的用戶信息到數據庫中為例,進行闡述relationalStore.RdbStore數據庫的CRUD相關操作
數據庫的使用
若是使用頻繁,可以創建一個單例類進行管理存儲到數據庫的用戶信息
export class UserProfileManagerUtil{private constructor() {}private static instance: UserProfileManagerUtil | null = nullpublic static getInstance(): UserProfileManagerUtil{if (UserProfileManagerUtil.instance == null) {UserProfileManagerUtil.instance = new UserProfileManagerUtil()}return UserProfileManagerUtil.instance}}
建表
定義表信息
通過SQL語句建立一個數據庫表。在此之前定義數據庫名稱和用戶信息表名以及用戶信息表中的字段,此處為了簡介,便只定義三個字斷
private static readonly DATABASE_NAME = "AppDataBase.db" //數據庫名稱private static readonly USER_PROFILE_TABLE_NAME = "UserProfile" //表名private static readonly COL_USERNAME = "USERNAME" private static readonly COL_AGE = "AGE" private static readonly COL_SEX = "SEX"
配置數據庫信息以及是否加密等
private static readonly STORE_CONFIG :relationalStore.StoreConfig= {name: UserProfileManagerUtil.DATABASE_NAME, // 數據庫文件名securityLevel: relationalStore.SecurityLevel.S1, // 數據庫安全級別encrypt: true // 可選參數,指定數據庫是否加密,默認不加密}
創建數據庫表
下列SQL語句格式需要特別注意,不然容易在創建表的時候出錯,下列以USERNAME
為主鍵
private static readonly CREATE_TABLE = "CREATE TABLE IF NOT EXISTS " + UserProfileManagerUtil.USER_PROFILE_TABLE_NAME + " ( " +UserProfileManagerUtil.COL_USERNAME + " TEXT PRIMARY KEY, " +UserProfileManagerUtil.COL_AGE + " INTEGER, " +UserProfileManagerUtil.COL_SEX + " INTEGER" +")"
創建數據庫操作對象
根據上面的數據庫配置信息和SQL建表語句,創建數據庫操作對象relationalStore.getRdbStore
同時需要注意的是應用創建的數據庫與其上下文(Context)有關,即使使用同樣的數據庫名稱,但不同的應用上下文,會產生多個數據庫,例如每個UIAbility都有各自的上下文。所以一般都在對應的UIAbility下先進行創建。確保在其UIAbility的可行性和唯一性
// 應用創建的數據庫與其上下文(Context)有關,即使使用同樣的數據庫名稱,但不同的應用上下文,會產生多個數據庫,例如每個UIAbility都有各自的上下文。async createDataBase(context: Context) {try {let store = await relationalStore.getRdbStore(context, UserProfileManagerUtil.STORE_CONFIG)if (store){this.storeInstance = storeawait this.storeInstance.executeSql(UserProfileManagerUtil.CREATE_TABLE) //創建數據庫}} catch (error) {Logger.error(`the result is failed of create DB,the cause is ${(error as BusinessError).message}`)}}
增
根據上述創建的數據庫操作對象進行插入操作,其中ValuesBucket
使用鍵值對的方式進行數據匹對
insertUserProfile(userProfile: UserProfileModel){let insertFormat: ValuesBucket = {'USERNAME' : userProfile.id,'AGE' : userProfile.avatar,'SEX' : userProfile.name}try {this.storeInstance?.insert(UserProfileManagerUtil.USER_PROFILE_TABLE_NAME, insertFormat, (err, rowId)=>{if (err) {Logger.error(`insert failed,the cause is ${err.message}`)return}//插入成功Logger.info(`insert successful,the rowId is ${rowId}`)})} catch (error) {Logger.error(`insert failed,the cause is ${(error as BusinessError).message}`)}}
更新
下列通過predicates.equalTo
查找數據庫表中對應的數據項,然后根據ValuesBucket
中的內容定位到需要進行數據更新的字段,下列以更新年齡為例子。
updateAge(primaryKey: string, age: number){try {let predicates = new relationalStore.RdbPredicates(UserProfileManagerUtil.USER_PROFILE_TABLE_NAME) // 創建表的predicates-謂詞predicates.equalTo(UserProfileManagerUtil.COL_USERNAME, primaryKey) // 匹配表中主鍵為key(username)的字段let updateFormat: ValuesBucket = {'AGE' : age}this.storeInstance?.update(updateFormat, predicates, (err: BusinessError, rows: number) => {if (err) {Logger.error(`update failed,the cause is ${err.message}`)return}//更新數據成功Logger.info(`update successful,the rowId is ${rows}`)})} catch (error) {Logger.error(`update failed,the cause is ${(error as BusinessError).message}`)}}
查詢
定義數據庫查詢SQL語句
let sql = "select * from " + UserProfileManagerUtil.USER_PROFILE_TABLE_NAME
通過querySql
查詢數據庫表中的內容,然后通過遍歷查詢結果,并取出其中的內容。其中getString(0)
后面的序號,為創建數據庫表時,字段的定義順序
async queryUserProfile(): Promise<Array<UserProfileModel>>{try {let sql = "select * from " + UserProfileManagerUtil.USER_PROFILE_TABLE_NAMElet result = await this.storeInstance?.querySql(sql)let array: Array<UserProfileModel> = []if(result) {while(result.goToNextRow()) {let username = result.getString(0)let age = result.getLong(1)let sex = result.getLong(2)array.push(new UserProfileModel(username,age,sex));}result.close()}return array} catch (error) {Logger.error(`query failed,the cause is ${(error as BusinessError).message}`)return null}}
刪
通過predicates.equalTo
比對數據庫表中數據項的主鍵,然后刪除對應列
deleteUserProfile(primaryKey: string){try {let predicates = new relationalStore.RdbPredicates(UserProfileManagerUtil.USER_PROFILE_TABLE_NAME) // 創建表的predicates-謂詞predicates.equalTo(UserProfileManagerUtil.COL_USERNAME, primaryKey) // 匹配表中主鍵為key(username)的字段this.storeInstance?.delete(predicates, (err: BusinessError, rows: number) => {if (err) {Logger.error(`delete failed,the cause is ${err.message}`)return}//刪除成功Logger.info(`delete successful,the rowId is ${rows}`)})} catch (error) {Logger.error(`delete failed,the cause is ${(error as BusinessError).message}`)}}
數據庫的初始化
可以在UIAbility
的派生類中進行數據庫創建,確保到當前Context的唯一性和可行性。避免在未初始化就調用,UIAbility
因此在入口處進行調用。
export default class EntryAbility extends UIAbility {async onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) {await UserProfileManagerUtil.getInstance().createDataBase(this.context) //創建數據庫
}