鸿蒙数据持久化sqlite

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%')
  }
}

 

posted @ 2024-10-11 13:22  龍飛鳯舞  阅读(45)  评论(0编辑  收藏  举报