鸿蒙加载预置数据库-关系型数据库-如何读取本地/预制数据库

参考文章如下

如何读取本地/预制数据库

案例下载
加载预置数据库刷新文章列表

保存数据库到沙箱

ts 复制代码
 function saveFileToCache(file: resourceManager.RawFileDescriptor, dbName: string, context: UIContext,
  bufferSize: number) {
  // let context = AppStorage.get("context") as UIContext;
  let RDBDirectory = context.getHostContext()!.databaseDir;

  // 创建缓存文件(当前是覆盖式创建)
  let cFile = RDBDirectory + '/customDir/rdb/' + dbName;
  let cacheFile = fileIo.openSync(cFile, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);

  // 读取缓冲区大小
  let buffer = new ArrayBuffer(bufferSize); //创建buffer缓冲区

  // 要copy的文件的offset
  let currentOffset = file.offset;

  let readOption: ReadOptions = {
    offset: currentOffset, //期望读取文件的位置。可选,默认从当前位置开始读
    length: bufferSize //每次期望读取数据的长度。可选,默认缓冲区长度
  };

  // 后面len会一直减,直到没有
  while (true) {
    // 读取buffer容量的内容
    let readLength = fileIo.readSync(file.fd, buffer, readOption);
    // 写入buffer容量的内容
    fileIo.writeSync(cacheFile.fd, buffer, { length: readLength }); //写到cacheFile里
    // 判断后续内容 修改读文件的参数
    // buffer没读满代表文件读完了
    if (readLength < bufferSize) {
      break;
    }
    if (readOption.offset != undefined) {
      readOption.offset += readLength;
    }
  }
  console.log('Copy Success!!!')
  fileIo.close(cacheFile);
}

async function INIT(context: UIContext, dbName: string, bufferSize: number) {

  let RDBDirectory = context.getHostContext()!.databaseDir;
  let resource = context.getHostContext()!.resourceManager;

  // 创建数据库沙箱目录
  try {
    let dirPath = RDBDirectory + '/customDir';
    fileIo.mkdirSync(dirPath);
    dirPath = dirPath + '/rdb';
    fileIo.mkdirSync(dirPath);
  } catch (error) {
    console.error(`mkdir rdbPath failed, error code: ${error.code}, message: ${error.message}.`);
  }

  //数据库名称传进来

  //读取rawfile目录下db文件
  try {
    const value: resourceManager.RawFileDescriptor = await resource.getRawFd('rdb/' + dbName)
    saveFileToCache(value, dbName, context, bufferSize);
  } catch (error) {
    console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
  }
}

预制数据库的读取封装

ts 复制代码
export async function getRDB(context: UIContext, name: string,customDir:string): Promise<relationalStore.RdbStore | undefined> {
  const RDBDirectory = context.getHostContext()!.databaseDir;
  console.log('RDBDirectory', RDBDirectory)
  let store: relationalStore.RdbStore | undefined = undefined;
  const STORE_CONFIG: relationalStore.StoreConfig = {
    name,
    securityLevel: relationalStore.SecurityLevel.S1,
    customDir
  };
  try {
    await relationalStore.getRdbStore(context.getHostContext(), STORE_CONFIG)
      .then(async (rdbStore: relationalStore.RdbStore) => {
        store = rdbStore;

      })
      .catch((err: BusinessError) => {
        console.error(`Get RdbStore failed, code is ${err.code},message is ${err.message}`);
      });
    return store
  } catch (e) {
    console.info(`errorgetRsssssssss${e}`);
    return undefined
  }
}

使用

复制代码
// 插入沙箱,/data/app/el2/100/database/com.***.***/customDir/rdb
  await INIT(context, 'book.db', 10224 * 1024)   
  
// 获取沙箱的数据库或者自己创建的关系型数据库
 await getRDB(context, 'jiongji100_dictionary.db','../customDir/rdb')
相关推荐
hqk43 分钟前
鸿蒙项目实战:手把手带你实现 WanAndroid 布局与交互
android·前端·harmonyos
TT_Close1 小时前
【Flutter×鸿蒙】一个"插队"技巧,解决90%的 command not found
flutter·harmonyos
悟空聊架构4 小时前
基于KaiwuDB在游乐场“刷卡+投币”双模消费系统中的落地实践
数据库·后端·架构
IvorySQL4 小时前
PostgreSQL 技术日报 (3月4日)|硬核干货 + 内核暗流一网打尽
数据库·postgresql·开源
进击的丸子7 小时前
虹软人脸服务器版SDK(Linux/ARM Pro)多线程调用及性能优化
linux·数据库·后端
NineData1 天前
NineData智能数据管理平台新功能发布|2026年1-2月
数据库·sql·数据分析
IvorySQL1 天前
双星闪耀温哥华:IvorySQL 社区两项议题入选 PGConf.dev 2026
数据库·postgresql·开源
Hcourage1 天前
鸿蒙工程获取C/C++代码覆盖
harmonyos
ma_king1 天前
入门 java 和 数据库
java·数据库·后端
jiayou641 天前
KingbaseES 实战:审计追踪配置与运维实践
数据库