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

目录标题

  • 关系型数据库的运行机制
  • 样例代码
    • 共通方法 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.rowCountconsole.log("test", "数据库中数据数量:" + rowCount) //没数据时返回-1或0if (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 = resultconsole.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) => voiditems: 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 = 0build() {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.mzph.cn/bicheng/45169.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

自建邮件服务器有哪些方法步骤与注意事项?

自建邮件服务器如何设置解析&#xff1f;邮件服务器怎么使用&#xff1f; 自建邮件服务器可以为个人或企业提供更多的灵活性和控制权&#xff0c;然而&#xff0c;这也是一个复杂且需要谨慎处理的任务。AokSend将探讨自建邮件服务器的基本方法步骤和需要注意的事项。 自建邮件…

逻辑回归(纯理论)

1.什么是逻辑回归&#xff1f; 逻辑回归是一种常用的统计学习方法&#xff0c;主要用于解决分类问题。尽管名字中包含"回归"&#xff0c;但它实际上是一种分类算法 2.为什么机器学习需要使用逻辑回归 1.二元分类 这是逻辑回归最基本和常见的用途。它可以预测某个事…

鸿蒙开发:Universal Keystore Kit(密钥管理服务)【HMAC(C/C++)】

HMAC(C/C) HMAC是密钥相关的哈希运算消息认证码&#xff08;Hash-based Message Authentication Code&#xff09;&#xff0c;是一种基于Hash函数和密钥进行消息认证的方法。 在CMake脚本中链接相关动态库 target_link_libraries(entry PUBLIC libhuks_ndk.z.so)开发步骤 生…

计算机SCI期刊,闭眼投,保证检索,命中率100%

一、期刊名称 Pervasive and Mobile Computing 二、期刊简介 期刊类型&#xff1a;SCI 学科领域&#xff1a;计算机 影响因子&#xff1a;3 中科院分区&#xff1a;3区 三、期刊简介 Pervasive and Mobile Computing Journal &#xff08;PMC&#xff09; 是一本高影响力…

基于前馈神经网络 FNN 实现股票单变量时间序列预测(PyTorch版)

前言 系列专栏:【深度学习:算法项目实战】✨︎ 涉及医疗健康、财经金融、商业零售、食品饮料、运动健身、交通运输、环境科学、社交媒体以及文本和图像处理等诸多领域,讨论了各种复杂的深度神经网络思想,如卷积神经网络、循环神经网络、生成对抗网络、门控循环单元、长短期记…

自定义View-渐变TextView(重点:绘制文本)

源码链接 夸克网盘分享 效果展示 分析 动态效果&#xff0c;使用Animator实现自定义View 继承TextView使用TextView的测量&#xff0c;不重写使用TextView的布局&#xff0c;不重写绘制-重写绘制 使用两种颜色绘制文本颜色占比不同&#xff0c;百分比从0~1 实现 自定义属性…

论文发表作图必备:训练结果对比,多结果绘在一个图片【Precision】【Recall】【mAP0.5】【mAP0.5-0.95】【loss】

前言:Hello大家好,我是小哥谈。YOLO(You Only Look Once)算法是一种目标检测算法,它可以在图像中实时地检测和定位目标物体。YOLO算法通过将图像划分为多个网格,并在每个网格中检测目标物体,从而实现快速的目标检测。本文所介绍的作图教程适用于所有YOLO系列版本算法,接…

Go泛型详解

引子 如果我们要写一个函数分别比较2个整数和浮点数的大小&#xff0c;我们就要写2个函数。如下&#xff1a; func Min(x, y float64) float64 {if x < y {return x}return y }func MinInt(x, y int) int {if x < y {return x}return y }2个函数&#xff0c;除了数据类…

Idea在线搜索Maven依赖-好用工具分享

maven_search 等价于网页搜索maven依赖&#xff0c;非常方便快捷 下载安装后&#xff0c;使用&#xff1a; 点击上方Tools Maven Search 或者快捷键 Ctrl Shift M 最后选择依赖&#xff0c;复制即可

Vue 3 与 TypeScript:最佳实践详解

大家好,我是CodeQi! 很多人问我为什么要用TypeScript? 因为 Vue3 喜欢它! 开个玩笑... 在我们开始探索 Vue 3 和 TypeScript 最佳实践之前,让我们先打个比方。 如果你曾经尝试过在没有 GPS 的情况下开车到一个陌生的地方,你可能会知道那种迷失方向的感觉。 而 Typ…

昇思学习打卡-17-热门LLM及其他AI应用/基于MobileNetv2的垃圾分类

文章目录 网络介绍读取数据集训练训练策略模型保存损失函数优化器模型训练 网络介绍 MobileNetv2专注于移动端、嵌入式或IoT设备的轻量级CNN网络。MobileNet网络使用深度可分离卷积&#xff08;Depthwise Separable Convolution&#xff09;的思想在准确率小幅度降低的前提下&…

分享一款嵌入式开源LED指示灯控制代码框架cotLed

一、工程简介 cotLed是一款轻量级的LED控制软件框架&#xff0c;可以十分方便地控制及自定义LED的各种状态&#xff0c;移植方便&#xff0c;无需修改&#xff0c;只需要在初始化时实现单片机硬件GPIO初始化&#xff0c;同时为框架接口提供GPIO写函数即可。 框架代码工程地址&a…

Apache Dubbo与Nacos整合过程

Dubbo服务发现 Dubbo 提供的是一种 Client-Based 的服务发现机制&#xff0c;依赖第三方注册中心组件来协调服务发现过程&#xff0c;支持常用的注册中心如 Nacos、Consul、Zookeeper 等。 以下是 Dubbo 服务发现机制的基本工作原理图&#xff1a; 服务发现包含提供者、消费者…

LabVIEW中使用 DAQmx Connect Terminals作用意义

该图展示了如何在LabVIEW中使用 DAQmx Connect Terminals.vi 将一个信号从一个源端口连接到一个目标端口。这种处理有以下几个主要目的和作用&#xff1a; 同步操作&#xff1a; 在多任务、多通道或多设备系统中&#xff0c;可能需要不同的组件在同一时刻执行某些操作。通过将触…

redis相关知识记录

redis基本数据类型 Redis⽀持五种主要数据结构&#xff1a;字符串&#xff08;Strings&#xff09;、列表&#xff08;Lists&#xff09;、哈希表&#xff08;Hashes&#xff09;、集合&#xff08;Sets&#xff09;和有序集合&#xff08;Sorted Sets&#xff09;。这些数据结…

winform4

json using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; //导入json第三方库 使用nuget搜索 …

断电的固态硬盘数据能放多久?

近日收到一个网友的提问&#xff0c;在这里粗浅表达一下见解&#xff1a; “网传固态硬盘断电后数据只能放一年&#xff0c;一年之后就会损坏。但是我有一个固态硬盘已经放了五六年了&#xff08;上次通电还是在2018年左右&#xff0c;我读初中的时候&#xff09;&#xff0c;…

《长相思》第二季回归:好剧质量,永恒的王牌

在万千剧迷的翘首以盼中&#xff0c;《长相思》第二季终于携着前作的辉煌与期待&#xff0c;缓缓拉开了序幕。这部自播出以来便以其精湛的剧情、出色的演员阵容以及独到的宣传策略&#xff0c;赢得了广泛好评与持续关注。如今&#xff0c;第二季的回归&#xff0c;无疑再次证明…

Linux 初识

目录 ​编辑 1.Linux发展史 1.1UNIX发展历史 1.2Linux发展历史 2.Linux的开源属性 2.1 开源软件的定义 2.2 Linux的开源许可证 2.3 开源社区与协作 3.Linux的企业应用现状 3.1 服务器 3.1.1 Web服务器 3.1.2 数据库服务器 3.1.3 文件服务器 3.1.4 电子邮件服务器 …

某客户管理系统Oracle RAC节点异常重启问题详细分析记录

一、故障概述 某日10:58分左右客户管理系统数据库节点1所有实例异常重启&#xff0c;重启后业务恢复正常。经过分析发现&#xff0c;此次实例异常重启的是数据库节点1。 二、故障原因分析 1、数据库日志分析 从节点1的数据库日志来看&#xff0c;10:58:49的时候数据库进程开始…