鴻蒙數據庫操作

一、使用關系型數據庫實現數據持久化,需要獲取一個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
英文地址,請注明出處:http://en.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;連接起永樂盛世的恢弘氣象與數字時代的文明重構。作為人工智能與歷史學…