在getRdbStore中,读取本地的数据库文件(非getRdbStore直接创建),报错如下图。
你的问题可以理解为如何读取本地/预制数据库吗?
如果是的话,试试以下两个步骤:
/data/app/el2/100/database/(bundleName)/entry/rdb/
下,实现方式为用文件管理的接口打开本地数据库,读取本地数据库内容并写入沙箱路径下的db文件中。import { fileIo, ReadOptions } from '@kit.CoreFileKit';
import { resourceManager } from '@kit.LocalizationKit';
import { relationalStore } from '@kit.ArkData';
let context = getContext(this);
let RDBDirectory = getContext(this).getApplicationContext().databaseDir;
let resource = getContext(this).resourceManager;
function saveFileToCache(file: resourceManager.RawFileDescriptor, dbName: string) {
// 创建缓存文件(当前是覆盖式创建)
let cFile = RDBDirectory + '/entry/rdb/' + dbName;
let cacheFile = fileIo.openSync(cFile, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
// 读取缓冲区大小
let bufferSize = 30000;
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);
}
function INIT() {
// 创建数据库沙箱目录
try {
let dirPath = RDBDirectory + '/entry';
fileIo.mkdirSync(dirPath);
dirPath = dirPath + '/rdb';
fileIo.mkdirSync(dirPath);
} catch (error) {
console.error(`mkdir rdbPath failed, error code: ${error.code}, message: ${error.message}.`);
}
//数据库名称
let dbName: string = 'Company.db';
//读取rawfile目录下db文件
try {
resource.getRawFd('rdb/' + dbName, (error, value) => {
if (error != null) {
console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`);
} else {
console.info(value.length.toString());
saveFileToCache(value, dbName);
}
});
} catch (error) {
console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
}
}
通过getRdbStore获取保存在沙箱路径下的db文件
function getRDB(): relationalStore.RdbStore | undefined {
let result: relationalStore.RdbStore | undefined = undefined;
const STORE_CONFIG: relationalStore.StoreConfig = {
name: 'Company.db',
securityLevel: relationalStore.SecurityLevel.S1
};
relationalStore.getRdbStore(context, STORE_CONFIG, (err, store) => {
if (err) {
console.error(`Failed to get RdbStore. Code:${err.code}, message:${err.message}`);
return;
} else {
console.info(`Succeeded in getting RdbStore.`);
}
result = store;
})
return result;
}
1 回答549 阅读✓ 已解决
1 回答556 阅读
1 回答590 阅读
1 回答504 阅读
1 回答502 阅读
519 阅读
510 阅读
解决方案
参考demo: