鸿蒙数据库操作

一、使用关系型数据库实现数据持久化,需要获取一个RdbStore,其中包括建库、建表、升降级等操作。

   const STORE_CONFIG: relationalStore.StoreConfig = {name: 'AnyOffice.db', // 数据库文件名securityLevel: relationalStore.SecurityLevel.S1, // 数据库安全级别encrypt: false, // 可选参数,指定数据库是否加密,默认不加密isReadOnly: false // 可选参数,指定数据库是否以只读方式打开。该参数默认为false,表示数据库可读可写。该参数为true时,只允许从数据库读取数据,不允许对数据库进行写操作,否则会返回错误码801。};relationalStore.getRdbStore(this.context, STORE_CONFIG, (err, store) => {if (err) {console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);return;}APPDataBaseHelper.getInstance().initialStore(store)APPDataBaseHelper.getInstance().initialize()})}

二、获取到RdbStore,完成数据表创建后,进行表的操作

import { relationalStore } from '@kit.ArkData';
import { BusinessError } from '@kit.BasicServicesKit';
import { IAppData } from '../pages/AppStore/AppStoreM';const TAG = 'APPDataBaseHelper:'
// 表名和字段定义
const TABLE_NAME = 'AnyOfficeApps';
const COLUMN_USER = 'user'
const COLUMN_APK_URL = 'apk'
const COLUMN_ID = 'appId'
const COLUMN_ICON_URL = 'iconURL'
const COLUMN_APP_NAME = 'appName'
const COLUMN_APP_VERSION = 'appVersion'
const COLUMN_APP_SIZE = 'appSize'
const COLUMN_APP_PACKAGE_NAME = 'packageName'
const COLUMN_APP_STATE = 'appState'const SQL_CREATE_TABLE =`CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (ID INTEGER PRIMARY KEY AUTOINCREMENT,${COLUMN_USER} TEXT,${COLUMN_APK_URL} TEXT,${COLUMN_ID} INTEGER NOT NULL,${COLUMN_ICON_URL} TEXT,${COLUMN_APP_NAME} TEXT UNIQUE NOT NULL,${COLUMN_APP_VERSION} TEXT,${COLUMN_APP_SIZE} INTEGER,${COLUMN_APP_PACKAGE_NAME} TEXT NOT NULL,${COLUMN_APP_STATE} INTEGER NOT NULL)`export class APPDataBaseHelper {private static instance: APPDataBaseHelperprivate rdbStore: relationalStore.RdbStore | null = null;private constructor() {}public static getInstance() {if (!APPDataBaseHelper.instance) {APPDataBaseHelper.instance = new APPDataBaseHelper()}return APPDataBaseHelper.instance}async initialStore(store: relationalStore.RdbStore): Promise<void> {this.rdbStore = store}//初始化表async initialize(): Promise<void> {if (!this.rdbStore) {return}if (this.rdbStore.version === 0) {// 创建表await this.rdbStore.executeSql(SQL_CREATE_TABLE).catch((err: BusinessError) => {console.error(`Database initialization failed. Code: ${err.code}, Message: ${err.message}`);return});console.info(`${TAG}Table created successfully.`);}}/*** 批量插入数据* @param apps* @returns*/async batchInsertApps(apps: IAppData[]): Promise<void> {if (!this.rdbStore || this.rdbStore === undefined) {throw new Error('Database not initialized. Call initialize() first.');}try {let userName = AppStorage.get<string>('userName')//开启事务this.rdbStore.beginTransaction()for (const app of apps) {const valueBucket: relationalStore.ValuesBucket = {user: userName ?? '',apk: app.apk,appId: app.id,iconURL: app.iconURL,appName: app.appName,appVersion: app.appVersion,appSize: app.appSize,packageName: app.packageName,appState: 0}const checkAppExist = await this.checkAppExist(app.packageName)if (!checkAppExist) {await this.rdbStore.insert(TABLE_NAME, valueBucket)}}//提交事务this.rdbStore.commit()console.info(`${TAG}Batch insert succeeded.`);} catch (err) {// 回滚事务this.rdbStore.rollBack();const error = err as BusinessError;console.error(`${TAG}Batch insert failed. Code: ${error.code}, Message: ${error.message}`);}}/*** 更新应用状态* @param id* @param state 0 未安装 1 已安装 2 待更新* @returns*/async updateAppState(id: number, state: number): Promise<boolean> {if (!this.rdbStore || this.rdbStore === undefined) {console.info(`${TAG}Database not initialized. Call initialize() first.`);return false}const valueBucket: relationalStore.ValuesBucket = {appState: state}let userName = AppStorage.get<string>('userName')const predicates = new relationalStore.RdbPredicates(TABLE_NAME);predicates.equalTo(`${COLUMN_ID}`, id).and().equalTo(`${COLUMN_USER}`, userName)const result = await this.rdbStore.update(valueBucket, predicates)console.info(`${TAG}updateAppState is ${result}`)return result > 0}/*** 查询所有app数据* @returns*/async queryAllApp(): Promise<IAppData[]> {if (!this.rdbStore || this.rdbStore === undefined) {console.info(`${TAG}Database not initialized. Call initialize() first.`);return []}let userName = AppStorage.get<string>('userName')const predicates = new relationalStore.RdbPredicates(TABLE_NAME);predicates.equalTo(`${COLUMN_USER}`, userName)const COLUMNS = [COLUMN_APK_URL, COLUMN_ID, COLUMN_ICON_URL, COLUMN_APP_NAME, COLUMN_APP_VERSION, COLUMN_APP_SIZE,COLUMN_APP_PACKAGE_NAME]try {const result = await this.rdbStore.query(predicates, COLUMNS)const apps: IAppData[] = []while (result.goToNextRow()) {const app: IAppData = {iconURL: result.getString(result.getColumnIndex(`${COLUMN_ICON_URL}`)),appName: result.getString(result.getColumnIndex(`${COLUMN_APP_NAME}`)),appVersion: result.getString(result.getColumnIndex(`${COLUMN_APP_VERSION}`)),appSize: result.getLong(result.getColumnIndex(`${COLUMN_APP_SIZE}`)),id: result.getLong(result.getColumnIndex(`${COLUMN_ID}`)),apk: result.getString(result.getColumnIndex(`${COLUMN_APK_URL}`)),packageName: result.getString(result.getColumnIndex(`${COLUMN_APP_PACKAGE_NAME}`))}apps.push(app)}result.close()return apps} catch (err) {const error = err as BusinessError;console.error(`Query failed. Code: ${error.code}, Message: ${error.message}`);return []}}/*** 获取所有已经安装的app* @returns*/async queryAllInstalledApp(): Promise<IAppData[]> {if (!this.rdbStore || this.rdbStore === undefined) {console.info('Database not initialized. Call initialize() first.');return []}let userName = AppStorage.get<string>('userName')const predicates = new relationalStore.RdbPredicates(TABLE_NAME);predicates.equalTo(`${COLUMN_APP_STATE}`, 1).and().equalTo(`${COLUMN_USER}`, userName)const COLUMNS = [COLUMN_APK_URL, COLUMN_ID, COLUMN_ICON_URL, COLUMN_APP_NAME, COLUMN_APP_VERSION, COLUMN_APP_SIZE,COLUMN_APP_PACKAGE_NAME]try {const result = await this.rdbStore.query(predicates, COLUMNS)const apps: IAppData[] = []while (result.goToNextRow()) {const app: IAppData = {iconURL: result.getString(result.getColumnIndex(`${COLUMN_ICON_URL}`)),appName: result.getString(result.getColumnIndex(`${COLUMN_APP_NAME}`)),appVersion: result.getString(result.getColumnIndex(`${COLUMN_APP_VERSION}`)),appSize: result.getLong(result.getColumnIndex(`${COLUMN_APP_SIZE}`)),id: result.getLong(result.getColumnIndex(`${COLUMN_ID}`)),apk: result.getString(result.getColumnIndex(`${COLUMN_APK_URL}`)),packageName: result.getString(result.getColumnIndex(`${COLUMN_APP_PACKAGE_NAME}`))}apps.push(app)}result.close()return apps} catch (err) {const error = err as BusinessError;console.error(`Query failed. Code: ${error.code}, Message: ${error.message}`);return []}}/*** 检查数据是否已存在* @param packageName* @returns*/async checkAppExist(packageName: string): Promise<boolean> {if (!this.rdbStore) {return false}let userName = AppStorage.get<string>('userName')const predicates = new relationalStore.RdbPredicates(TABLE_NAME);predicates.equalTo(`${COLUMN_APP_PACKAGE_NAME}`, packageName).and().equalTo(`${COLUMN_USER}`, userName);const resultSet = await this.rdbStore.query(predicates, [`${COLUMN_APP_PACKAGE_NAME}`])let exist=resultSet.rowCount>0resultSet.close()return exist}
}

三、官网文档连接

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

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

相关文章

基于ARM SoC的半导体测试

ARM SoC&#xff08;System on Chip&#xff09; 是一种集成了多个关键计算组件的单片系统芯片&#xff0c;广泛应用于移动设备、嵌入式系统、物联网&#xff08;IoT&#xff09;和半导体测试设备等领域。它的核心设计理念是“高度集成”&#xff0c;将处理器、内存、外设接口等…

JavaEE->多线程2

目录 一、线程安全&#xff08;重点&#xff09; 1.线程安全演示 2.线程不安全的原因 1.线程是抢占式执行的&#xff08;执行顺序是随机的&#xff09; 2.多个线程同时修改了同一个变量 3.原子性 4.内存可见性 5.指令重排序&#xff08;有序性&#xff09; 二、解决线…

Flutter TCP通信

启动TCP服务 Future<void> startServer() async {final server await ServerSocket.bind(InternetAddress.anyIPv4, 12345);print(Server listening on ${server.address}:${server.port});server.listen((Socket socket) {print(Client connected: ${socket.remoteAddr…

flask拆分计划

两个启动链接&#xff0c;看日志提示是因为2次启动&#xff0c;一次是database&#xff0c;一次是xmind2&#xff0c;去掉一次就可以&#xff0c;如何去掉一次&#xff1f; 这里启动也调用了一次&#xff0c;所以测试环境注释掉&#xff0c;如下图&#xff0c;也就调用了一次

【生活】ECMO原理、作用、费用及使用方法

博客目录 一、ECMO 是什么&#xff1f;二、ECMO 的作用1. 替代肺功能&#xff08;氧合与二氧化碳清除&#xff09;2. 替代心脏功能&#xff08;循环支持&#xff09;3. 为其他治疗争取时间4. 用于心肺复苏&#xff08;ECPR&#xff09; 三、ECMO 的费用1. 设备使用费2. 耗材费用…

Profinet转EtherCAT网关模块怎么用:案例分享

在某制造工厂西门子S7-1200 PLC中&#xff0c;存在一个技术难题&#xff0c;即伺服驱动器与可编程逻辑控制器&#xff08;PLC&#xff09;之间的通讯不兼容问题。具体而言&#xff0c;PLC采用的是PROFINET通讯协议&#xff0c;而伺服EtherCAT协议驱动器则需要EtherCAT协议进行数…

什么是 NLP-NLP基础知识体系的系统认知

NLP基础知识体系的系统认知 一、引言 今天的学习内容集中于自然语言处理&#xff08;NLP&#xff09;的基本概念、发展历程、核心任务及文本表示技术。通过这一学习过程&#xff0c;我对NLP这门学科有了更加系统和深入的认识&#xff0c;并且理解了NLP技术的广泛应用及其复杂…

数据结构 学习 链表 2025年6月14日08点01分

单向链表: 线性数据结构 由一系列节点组成 每个节点包含: 数据部分:存储实际数据 指针部分:储存指向下一个节点的引用 特点1,每个节点只有一个指向下一个节点的指针 特点2,只能从头到尾 单向遍历 特点3,不需要连续的内存空间 特点4,插入和删除效率高 特点5,随机访问 效率低 …

使用 Kubernetes 部署 PHP 留言板应用(含 Redis 架构)

使用 Kubernetes 部署 PHP 留言板应用&#xff08;含 Redis 架构&#xff09; 文章目录 使用 Kubernetes 部署 PHP 留言板应用&#xff08;含 Redis 架构&#xff09;教程概述技术架构特点 准备工作环境要求 Redis 数据库部署Redis 主从架构原理创建 Redis 领导者 Deployment部…

MATLAB提供的两种画误差矩阵的函数

MATLAB在统计学和机器学习工具包中提供了两种画误差矩阵&#xff08;Confusion matrix&#xff09;的函数。 figure; plotconfusion(YValidation,YPred)figure; cm confusionchart(YValidation,YPred) cm.Title Confusion Matrix for Validation Data; cm.RowSummary row-n…

【Java学习笔记】泛型

泛型 一、泛型的引出 代码示例 public class pra {public static void main(String[] args) {ArrayList arrayList new ArrayList();arrayList.add("java");arrayList.add("jack");arrayList.add("jom");arrayList.add(new a());for (Object…

SpringMVC系列(一)(介绍,简单应用以及路径位置通配符)

0 引言 作者正在学习SpringMVC相关内容&#xff0c;学到了一些知识&#xff0c;希望分享给需要短时间想要了解SpringMVC的读者朋友们&#xff0c;想用通俗的语言讲述其中的知识&#xff0c;希望与诸位共勉&#xff0c;共同进步&#xff01; 1 SpringMVC介绍 SpringMVC本质上…

Java中如何使用lambda表达式分类groupby

Java中如何使用lambda表达式分类groupby Java中如何使用lambda表达式分类groupby分类问题场景传统手写方式lambda使用groupBy()方法一行结束&#xff01;&#xff01;&#xff01;完整代码 Java中如何使用lambda表达式分类groupby 分类问题场景 比如一群学生根据性别和年龄排…

无人机开发分享——无人机集群基于braft实现长机动态推选算法

在无人机集群项目的算法开发中&#xff0c;推选长机作为集群的动态中心&#xff0c;往往承担着集群管理、通讯中继等重要功能。由于通讯链路的有限性和任务的实时性需要&#xff0c;需要保证动态长机时刻工作正常&#xff0c;并在异常情况下快速切换新长机。 本文主要分享基于b…

python 解码 jwt

import base64 import jsondef base64url_decode(base64url_data):# 将URL安全的base64编码数据转换为标准的base64编码数据base64_data base64url_data.replace(-, ).replace(_, /)# 如果数据长度不是4的倍数&#xff0c;则补齐padding_length 4 - len(base64_data) % 4base…

腾讯云TCCA认证考试报名 - TDSQL数据库交付运维工程师(MySQL版)

数据库交付运维工程师-腾讯云TDSQL(MySQL版)认证 适合人群&#xff1a; 适合从事TDSQL(MySQL版)交付、初级运维、售前咨询以及TDSQL相关项目的管理人员。 认证考试 单选*40道多选*20道 成绩查询 70分及以上通过认证&#xff0c;官网个人中心->认证考试 查询 考试费用&am…

Spring Boot的Security安全控制——认识SpringSecurity!

Spring Boot的Security安全控制 在Web项目开发中&#xff0c;安全控制是非常重要的&#xff0c;不同的人配置不同的权限&#xff0c;这样的系统才安全。最常见的权限框架有Shiro和Spring Security。Shiro偏向于权限控制&#xff0c;而Spring Security能实现权限控制和安全控制…

深入理解ArrayList:从Java原生实现到手写一个ArrayList

Java原生ArrayList解析 基本结构 Java的ArrayList是基于数组实现的动态列表&#xff0c;主要特点包括&#xff1a; 动态扩容&#xff1a;当元素数量超过当前容量时&#xff0c;自动扩容&#xff08;通常增加50%&#xff09; 快速随机访问&#xff1a;通过索引访问元素的时间…

【力扣 简单 C】206. 反转链表

目录 题目 解法一&#xff1a;迭代 解法二&#xff1a;递归 题目 解法一&#xff1a;迭代 struct ListNode* reverse(struct ListNode* head) {struct ListNode* retHead NULL;while (head){struct ListNode* nextNode head->next;head->next retHead;retHead he…

明代大模型:智能重构下的文明再发现

引言&#xff1a;当紫禁城遇见生成式AI 一幅动态的《紫禁城图卷》正通过全息投影技术演绎永乐年间的宫廷盛景。这个虚实交融的场景&#xff0c;恰似明代大模型技术的隐喻——以人工智能为纽带&#xff0c;连接起永乐盛世的恢弘气象与数字时代的文明重构。作为人工智能与历史学…