【鸿蒙学习笔记】关系型数据库概述

目录标题

  • 关系型数据库的运行机制
  • 样例代码
    • 共通方法 DBUtils
    • Index 代码
    • 效果

关系型数据库的运行机制

1、 关系型数据库对应用提供通用的操作接口,底层使用SQLite作为持久化存储引擎,支持SQLite具有的数据库特性,包括但不限于事务、索引、视图、触发器、外键、参数化查询和预编译SQL语句。
在这里插入图片描述

样例代码

共通方法 DBUtils

import relationalStore from '@ohos.data.relationalStore'
import { common } from '@kit.AbilityKit'

export class DBUtils {
  // 数据库名称
  private tableName: string = 'accountTable'
  // 建表语句
  private sqlCreate: string = 'CREATE TABLE IF NOT EXISTS accountTable(id INTEGER PRIMARY KEY AUTOINCREMENT, accountType INTEGER, typeText TEXT, amount INTEGER)'
  // 表字段
  private columns: string[] = ['id', 'accountType', 'typeText', 'amount']
  // 数据库核心类
  private rdbStore: relationalStore.RdbStore | null = null
  // 数据库配置
  DB_CONFIG: relationalStore.StoreConfig = {
    name: 'RdbTest.db', // 数据库文件名
    securityLevel: relationalStore.SecurityLevel.S1, // 数据库安全级别
  };

  /**
   * 获取rdb
   * @param context:上下文
   * @param callback:回调函数,我们第一次获取数据时,需要在获取到rdb之后才能获取,所以有此回调
   */
  getRdbStore(context: common.UIAbilityContext, callback: Function) {
    relationalStore.getRdbStore(context, this.DB_CONFIG, (error, store) => {
      if (this.rdbStore !== null) {
        //如果已经有rdb,直接建表
        store.executeSql(this.sqlCreate)
        return
      }
      //保存rdb,下边会用
      this.rdbStore = store
      //建表
      store.executeSql(this.sqlCreate)
      console.log("test", "successed get dbStore")
      if (callback) callback()
    })
  }

  /**
   * 插入数据
   * @param data:数据对象
   * @param callback:回调函数,这里的结果是通过回调函数返回的(也可使用返回值)
   */
  insertData(data: AccountData, callback: Function) {
    //将数据对象,转换为ValuesBucket类型
    const valueBucket: relationalStore.ValuesBucket = generateValueBucket(data);
    // 调用insert插入数据
    this.rdbStore && this.rdbStore.insert(this.tableName, valueBucket, (err, res) => {
      if (err) {
        console.log("test,插入失败", err)
        callback(-1)
        return
      }
      console.log("test,插入成功", res)
      callback(res) //res为行号
    })
  }

  /**
   * 获取数据
   * @param callback:接收结果的回调函数
   */
  query(callback: Function) {
    //predicates是用于添加查询条件的
    let predicates = new relationalStore.RdbPredicates(this.tableName)

    // 查询所有,不需要条件
    // predicates.equalTo("字段",数据)
    this.rdbStore && this.rdbStore.query(predicates, this.columns, (error, resultSet: relationalStore.ResultSet) => {
      if (error) {
        console.log("test,获取数据失败", JSON.stringify(error))
        return
      }

      let rowCount: number = resultSet.rowCount
      console.log("test", "数据库中数据数量:" + rowCount) //没数据时返回-1或0
      if (rowCount <= 0 || typeof rowCount === 'string') {
        callback([])
        return
      }

      let result: AccountData[] = []
      //上来必须调用一次goToNextRow,让游标处于第一条数据,while(resultSet.goToNextRow())是最有写法
      while (resultSet.goToNextRow()) {
        let accountData: AccountData = { id: 0, accountType: 0, typeText: '', amount: 0 }
        accountData.id = resultSet.getDouble(resultSet.getColumnIndex('id'));
        accountData.typeText = resultSet.getString(resultSet.getColumnIndex('typeText'))
        accountData.accountType = resultSet.getDouble(resultSet.getColumnIndex('accountType'))
        accountData.amount = resultSet.getDouble(resultSet.getColumnIndex('amount'))
        result.push(accountData)
      }
      callback(result)
      resultSet.close() //释放数据集内容
    })
  }
}

function generateValueBucket(account: AccountData): relationalStore.ValuesBucket {
  let obj: relationalStore.ValuesBucket = {};
  obj.accountType = account.accountType;
  obj.typeText = account.typeText;
  obj.amount = account.amount;
  return obj;
}

export class AccountData {
  id: number = -1;
  accountType: number = 0;
  typeText: string = '';
  amount: number = 0;
}

Index 代码

import { AccountData, DBUtils } from '../uitls/DBUtils';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct Index_DBPage {
  // 数据库工具类
  private dbUtils: DBUtils = new DBUtils()
  private context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext

  // 账户数据数组
  @State accountDataArray: AccountData[] = []
  // 列表的图片数组
  imageArr: Resource[] = [$r('app.media.foods'), $r('app.media.games'), $r('app.media.fuel')]

  // 添加数据弹框
  addDialogController: CustomDialogController = new CustomDialogController({
    builder: AddDialog({
      //点击确定的回调
      confirm: (insertData: AccountData) => {
        this.onConfirm(insertData)
      }
    })
  })

  // 界面打开时,查询数据,展示胡静
  aboutToAppear(): void {
    this.dbUtils.getRdbStore(this.context, () => {
      this.queryData()
    })
  }

  // 查询数据方法
  queryData() {
    this.dbUtils.query((result: AccountData[]) => {
      this.accountDataArray = result
      console.log("test,获取数据成功:", JSON.stringify(this.accountDataArray))
    })
  }

  // 点击确定回调
  onConfirm(insertData: AccountData) {
    console.log("test", JSON.stringify(insertData))
    // 插入数据
    this.dbUtils.insertData(insertData, (res: number) => {
      if (res > 0) {
        // AlertDialog.show({ message: "添加成功" })
        this.queryData()
      } else {
        AlertDialog.show({ message: "添加失败" })
      }
    })
  }

  build() {
    Stack() {
      Column() {
        Row() {
          Text('关系型数据库').height(33).fontSize(24).margin({ left: 24 }).fontColor(Color.Red)
        }.width('100%').justifyContent(FlexAlign.SpaceBetween).margin(12).backgroundColor(Color.Grey)

        //数据列表
        List({ space: 20 }) {
          ForEach(this.accountDataArray, (item: AccountData, index: number) => {
            ListItem() {
              Row() {
                // 图片
                Image(this.imageArr[item.accountType]).width(40).aspectRatio(1).margin({ right: 16 })
                // 内容
                Text(item.typeText).height(22).fontSize(16)
                Blank().layoutWeight(1)
                // 金额
                Text("¥: " + String(item.amount)).height(22).fontSize(16)
              }
              .width('90%')
              .padding({ left: 12, right: 12 })
              .margin({ left: 20 })
              .backgroundColor('#f1f3f5')
              .padding(10)
              .borderRadius(30)
            }
          })
        }
      }.width('100%')

      Button() {
        Image($r('app.media.add'))
      }.width(48).height(48).position({ x: '80%', y: '90%' })
      .onClick(() => {
        this.addDialogController.open()
      })
    }
  }
}

interface Item {
  icon: Resource;
  text: string;
}

@CustomDialog
struct AddDialog {
  controller: CustomDialogController;
  //确认回调
  confirm?: (insertData: AccountData) => void

  items: Array<Item> = [
    { icon: $r('app.media.foods'), text: '吃饭' },
    { icon: $r('app.media.games'), text: '娱乐' },
    { icon: $r('app.media.fuel'), text: '加油' },
  ]

  @State currentIndex: number = -1
  @State money: number = 0

  build() {
    Column() {
      Row() {
        ForEach(this.items, (item: Item, index) => {
          Column() {
            Image(item.icon).width(40).height(40)
            Text(item.text).fontSize(12).fontColor('#FF007DFF').margin({ top: 8 })
          }
          .width(86)
          .aspectRatio(1) //指定当前组件的宽高比
          .padding({ top: 12 })
          .margin({ top: 16, left: 12 })
          .align(Alignment.TopStart)
          .backgroundColor(this.currentIndex === index ? '#ccc' : '#FFF1F3F5')
          .borderRadius(16)
          .onClick(() => {
            this.currentIndex = index
          })
        })
      }.width('100%').justifyContent(FlexAlign.Center)

      Row() {
        Column() {
          Text('金额').width('100%').fontSize(20).fontColor(Color.Black)

          Column() {
            TextInput({
              placeholder: '请输入金额'
            })
              .padding({ left: 0, top: 0, bottom: 0 })
              .borderRadius(0)
              .backgroundColor(Color.White)
              .type(InputType.Number)
              .onChange((value: string) => {
                this.money = Number(value)
              })
          }.height(48).padding({ top: 15, bottom: 11 }).borderWidth({ bottom: 1 }).borderColor('#33182431')

          Button("确定").onClick((event: ClickEvent) => {
            if (this.currentIndex === -1) {
              AlertDialog.show({ message: "请选择种类" })
              return
            }
            if (this.money === 0) {
              AlertDialog.show({ message: "请输入金额" })
              return
            }
            let insertData: AccountData = {
              id: 0,
              accountType: this.currentIndex,
              typeText: this.items[this.currentIndex].text,
              amount: this.money
            }
            this.confirm && this.confirm(insertData)
            this.controller.close()
          }).width('90%').margin(20)
        }.width('100%').padding({ left: 12, right: 12 })
      }.width('100%').margin(20)
    }
  }
}

效果

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/794356.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

精密制造,光纤激光打标机在电子通讯行业的深度实践

光纤激光打标机&#xff0c;作为激光加工领域的一项先进技术&#xff0c;近年来在电子通讯行业中得到了广泛应用。它利用掺稀土元素玻璃光纤作为增益介质的激光器&#xff0c;通过光纤放大器开发出高功率密度的激光束&#xff0c;对工件表面进行精细加工&#xff0c;形成永久性…

强制升级最新系统,微软全面淘汰Win10和部分11用户

说出来可能不信&#xff0c;距离 Windows 11 正式发布已过去整整三年时间&#xff0c;按理说现在怎么也得人均 Win 11 水平了吧&#xff1f; 然而事实却是&#xff0c;三年时间过去 Win 11 占有率仅仅突破到 29%&#xff0c;也就跳起来摸 Win 10 屁股的程度。 2024 年 6 月 Wi…

Visual Studio 2022 安装及使用

一、下载及安装 VS 官网&#xff1a;Visual Studio: IDE and Code Editor for Software Developers and Teams 下载免费的社区版 得到一个.exe文件 右键安装 选择C开发&#xff0c;并修改安装位置 等待安装 点击启动 二、VS的使用 1.创建项目 打开VS&#xff0c;点击创建新项…

Ubuntu22.04安装NIVIDIA显卡驱动总结

1.首先在安装驱动时需要判断系统有无GPU以及GPU的型号 可以参考这篇文章&#xff1a; https://blog.51cto.com/u_13171517/8814753#:~:textubuntu%20%E7%B3%BB%E7%BB%9F%20%E6%80%8E%E4%B9%88%E5%88%A4%E6%96%AD%E7%B3%BB%E7%BB%9F%E6%9C%89%E6%B2%A1%E6%9C%89GPU%201%20%E6%…

批量提取PDF中表格内容

1 背景 从PDF文件获取表格中的数据&#xff0c;也是日常办公容易涉及到的一项工作。比如我们想获取某公司年报里面的表格数据&#xff0c;PDF动辄上百页的数据。 2 传统方法 一个一个从PDF表格中复制&#xff0c;然后粘贴到Excel表格中&#xff0c;效率太低了。 3 办公自动…

【OC】巧用UIStackView简化布局

UIStackView的运用 文章目录 UIStackView的运用引入UIStackView的作用UIStackView的属性compression resistance 和 huggingaxisalignmentDistributionspacing UIStackView的方法UIStackView的示例 引入 在仿写ZARA的过程之中&#xff0c;我看到软件之中是有大量的按钮排列在一…

一文带你掌握SpringMVC扩展点RequestBodyAdvice和ResponseBodyAdvice如何使用及实现原理

1.概述 Spring MVC是当今web项目系统开发后端技术框架的不二之选&#xff0c;也是Spring全家桶中非常重要的一个成员&#xff0c;它的设计思想和实现套路都是很值得我们学习的&#xff0c;所以今天我们就再来看看Spring MVC框架中预留的两个钩子也就是扩展点&#xff1a;Reque…

minio在redhat7.9上面的单节点单驱动离线安装(docker)

问题 最近需要在红帽上面离线安装minio&#xff0c;并且还是要离线安装到服务器中的Docker里面去。 检查服务器磁盘 # lsblk -f NAME FSTYPE LABEL UUID MOUNTPOINT sda ├─sda1 xfs xxxxsx-xxx-xxx…

如何基于大模型开发应用接口

一、前言 针对自然语言处理方向&#xff0c;以前要开发一个情感分析、命名实体识别之列的应用是非常麻烦的&#xff0c;我们需要完成收集数据、清理数据、构建模型、训练模型、调优模型等一系列操作&#xff0c;每一步都非常耗时。如今大语言模型&#xff08;LLM&#xff09;的…

【BUG】已解决:JsonMappingException

已解决&#xff1a;JsonMappingException 欢迎来到英杰社区https://bbs.csdn.net/topics/617804998 概述&#xff1a; 没有getter方法的实体的序列化&#xff0c;并解决Jackson引发的JsonMappingException异常。 默认情况下&#xff0c;Jackson 2只会处理公有字段或具有公有get…

RK3588部署YOLOV8-seg的问题

在使用YOLOV8-seg训练出来的pt模型转为onnx的时候&#xff0c;利用以下仓库地址转。 git clone https://github.com/airockchip/ultralytics_yolov8.git 在修改ultralytics/cfg/default.yaml中的task&#xff0c;mode为model为自己需要的内容后&#xff0c; 执行以下语句 cd …

2006-2021年 291个地级市资源错配指数、劳动和资本相对扭曲指数do文件和结果

资源错配指数&#xff1a;衡量生产要素配置效率的关键指标 资源错配指数&#xff08;Misallocation Index&#xff09;是一个衡量资源配置效率的指标&#xff0c;它反映了生产要素是否得到了合理配置&#xff0c;以及是否达到了生产效率的最优状态。一个较高的资源错配指数意味…

视图库对接系列(GA-T 1400)十六、视图库对接系列(本级)通知(订阅回调)

说明 之前我们实现了订阅接口,其中有一个receiveAddr参数, 这个就是对应的回调的地址。一般情况下对应的是同一个服务。 我们推荐使用http://xxx:xxx/VIID/SubscribeNotifications接口文档 SubscribeNotificationList对象对象如下: 文档中是xml,但实际上目前使用的都是jso…

传音控股Android一面凉经(2024)

传音控股Android一面凉经(2024) 笔者作为一名双非二本毕业7年老Android, 最近面试了不少公司, 目前已告一段落, 整理一下各家的面试问题, 打算陆续发布出来, 供有缘人参考。今天给大家带来的是《传音控股Android一面凉经(2024)》。 面试职位: Android应用开发工程师(移动互联业…

Python酷库之旅-第三方库Pandas(017)

目录 一、用法精讲 41、pandas.melt函数 41-1、语法 41-2、参数 41-3、功能 41-4、返回值 41-5、说明 41-5-1、宽格式数据(Wide Format) 41-5-2、长格式数据(Long Format) 41-6、用法 41-6-1、数据准备 41-6-2、代码示例 41-6-3、结果输出 42、pandas.pivot函数 …

新旧电脑数据转移方法

随着科技的发展和电脑性能的不断提升&#xff0c;许多用户在工作和生活中都需要更换新电脑。当我们购买了一台新电脑后&#xff0c;如何将旧电脑中的数据转移到新电脑上成许多用户关注的问题。本文将详细介绍几种有效的电脑数据转移方法&#xff0c;帮助大家顺利完成数据迁移。…

5G AGV 安全演示:解决新欧盟机器指令挑战

2024 年 2 月 26 日至 2 月 29 日&#xff0c;2024 世界移动通信大会&#xff08;MWC2024&#xff09;在西班牙巴塞罗那召开。 这场以「未来先行」为主题的大会&#xff0c;吸引了大量通信领域企业和观众参加&#xff0c;现场盛况空前。 HMS Labs 在与易福门&#xff08;ifm&am…

07_Shell内置命令-declare

07_Shell内置命令-declare 一、设置变量属性 - 增加属性 取消属性 1.1、设置变量为整形变量 declare -i 变量名 #!/bin/bashage"abc" #设置变量为整形变量&#xff0c;这时候age如果不是整形&#xff0c;则置为0 declare -i age echo $age#并且设置非整形值无效, 只…

不会写提示词的,快下载这个“老六”插件(附插件)

在AI绘画的世界里&#xff0c;每一个细节都至关重要&#xff0c;面对复杂的提示词——SixGod_k插件&#xff0c;只需轻点即可获得提示词&#xff0c;sd-webui中文提示词插件、老手新手炼丹必备。 一、SixGod_k提示词的功能亮点 SixGod_k提示词不仅解决了提示词编写的难题&…

MybatisPlus 核心功能

MybatisPlus 核心功能 文章目录 MybatisPlus 核心功能1. 条件构造器1.1 QueryWrapper1.2 LambdaQueryWrapper&#xff08;推荐&#xff09;1.3 UpdateWrapper1.4 LambdaUpdateWrapper 2. 自定义SQL3. Service接口 1. 条件构造器 当涉及到查询或修改语句时&#xff0c;MybatisP…