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

参考文章如下

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

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

保存数据库到沙箱

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')
相关推荐
纆兰36 分钟前
MySQL的多表查询
数据库·mysql
七夜zippoe37 分钟前
Nexent 模型配置:4 字段与 9 个槽位
数据库·人工智能·模型·nexent
进击的荆棘1 小时前
MySQL——表的操作
数据库·mysql
nice_lcj5203 小时前
MySQL 慢查询与 EXPLAIN:怎么定位、怎么优化
java·数据库·后端·mysql
威哥爱编程3 小时前
模拟面试智能体开发实战 09:把面试官装进手机,鸿蒙端聊天界面用 SSE 流式输出让回复逐字滚出来
python·agent·harmonyos
威哥爱编程3 小时前
模拟面试智能体开发实战 10:配置写死在代码里还怎么换服务端,把设置和简历做成界面可配、可存
python·agent·harmonyos
OceanRoy13 小时前
数据库表的设计
数据库·内连接·外连接·er图·表的约束·三大范式·多表连接
Pniubi13 小时前
怎么排查慢SQL,怎么解决?
java·数据库·sql
Decay__17 小时前
VMware 安装 SQL Server 双节点 AlwaysOn 可用性组教程 —— WSFC、AG 与侦听器完整部署(系列核心篇)
运维·数据库·sql·mysql·架构
茶栀(*´I`*)18 小时前
SQL 性能分析:从慢查询日志到执行计划的完整定位方法
数据库·sql