鴻蒙資料持久化sqlite

龍飛鳯舞發表於2024-10-11

1. 資料查詢model: entry/src/main/model/TaskModel.ets

import relationalStore from '@ohos.data.relationalStore';
import { common } from '@kit.AbilityKit';
import TaskInfo from '../ets/viewModel/TaskInfo';

class TaskModel {
  private rdbStore: relationalStore.RdbStore | undefined
  private tableName: string = 'TASK'

  /**
   * 初始化任務表
   */
  initTaskDB(context: common.UIAbilityContext) {
    // 1. rdb配置
    const config: relationalStore.StoreConfig = {
      name: 'MyApplication.db',
      securityLevel: relationalStore.SecurityLevel.S1
    }
    // 2. 初始化sql語句
    const sql = `CREATE TABLE IF NOT EXISTS TASK(
                   ID INTEGER PRIMARY KEY AUTOINCREMENT,
                   NAME TEXT NOT NULL,
                   FINISHED bit
                  )`
    // 3. 獲取rdb
    relationalStore.getRdbStore(context, config, (err, rdbStore: relationalStore.RdbStore) => {
      if (err) {
        console.log('testTag', '獲取rdbStore失敗')
      }

      rdbStore.executeSql(sql)
      this.rdbStore = rdbStore
      console.error("testTag","資料庫初始化成功")
    })
  }

  /**
   * 查詢任務資料
   */
  getTaskList(): Array<TaskInfo> {
    let tasks: TaskInfo[] = []
    let predicates = new relationalStore.RdbPredicates(this.tableName)
    /*構建查詢條件*/
    // predicates.equalTo('id','1')
    /*查詢資料*/
    if (this.rdbStore !== undefined) {
      let result = this.rdbStore.querySync(predicates, ['ID', 'NAME', 'FINISHED'])
      while (!result.isAtLastRow) { /*迴圈結果集*/
        result.goToNextRow()
        let id = result.getLong(result.getColumnIndex('ID'))
        let name = result.getString(result.getColumnIndex('NAME'))
        let finished = result.getLong(result.getColumnIndex('FINISHED'))
        let task = new TaskInfo(id, name, !!finished)
        tasks.push(task)
      }
    }
    return tasks;
  }

  /**
   * 新增任務
   */
  addTask(name: string) {
    return this.rdbStore?.insert(this.tableName, { name, finished: false })
  }

  /**
   * 更新任務狀態
   */
  updateTaskStatus(id: number, finished: boolean) {
    let predicates = new relationalStore.RdbPredicates(this.tableName)
    predicates.equalTo('ID', id)
    return this.rdbStore?.update({ finished }, predicates)
  }

  /**
   * 刪除任務
   */
  delTaskById(id: number) {
    let predicates = new relationalStore.RdbPredicates(this.tableName)
    predicates.equalTo('ID', id)
    return this.rdbStore?.delete(predicates)
  }
}

let taskModel = new TaskModel()

export default taskModel as TaskModel

2. 資料類:entry/src/main/ets/viewModel/TaskInfo.ets

export default class TaskInfo {
  id: number
  name: string
  finished: boolean

  constructor(id: number, name: string, finished: boolean = false) {
    this.id = id
    this.name = name
    this.finished = finished
  }
}

3. 初始化資料表 entry/src/main/ets/entryability/EntryAbility.ets 中 onWindowStageCreate 方法中新增

/*初始化資料表*/
 taskModel.initTaskDB(this.context)

4. 使用增刪改查:entry/src/main/ets/pages/Sqlite.ets

import taskModel from '../../model/TaskModel'
import TaskInfo from '../viewModel/TaskInfo'
import { JSON } from '@kit.ArkTS';

@Entry
@Component
struct Sqlite {
  @State message: string = 'Hello World';

  build() {
    Column() {
      Button("新增資料").onClick(() => {
        taskModel.addTask('任務1')
      })
      Button("修改資料").onClick(() => {
          taskModel.updateTaskStatus(1,true)
        })
      Button("查詢資料").onClick(() => {
        let res:TaskInfo[] = taskModel.getTaskList()
        console.info('taskList',JSON.stringify(res))
      })
      Button("刪除資料").onClick(() => {
        taskModel.delTaskById(1)
      })

    }
    .height('100%')
    .width('100%')
  }
}

相關文章