【解决方案】
RdbStore支持读取沙箱目录下的.mbtiles文件,无法读取可能有:
- 文件路径不正确、文件不存在。
- 文件损坏。
- 查询条件导致结果集为空。
请检查文件路径是否正确、文件是否存在、文件是否损坏以及查询条件是否正常,开发时可使用Device File Browser选择sanbox view模式(应用沙箱视图)查看沙箱文件。
参考代码如下:
// \uni-app-x工程目录\pages\index\index.uvue
<template>
<view>
<text>{{ title }}</text>
<button @click="downloadFile">点击下载</button>
<button @click="queryDatabase">点击查询</button>
</view>
</template>
<script>
import { saveFileToSandbox, query } from "../../uni_modules/lsk-rdb"
export default {
data() {
return {
title: 'Hello'
}
},
methods: {
downloadFile() {
try {
uni.showLoading();
uni.downloadFile({
url: ".mbtiles文件地址",
success: (res) => {
console.info(res.tempFilePath)
saveFileToSandbox(res.tempFilePath)
},
fail: (err) => {
console.info('downloadFile fail, err is:', err)
},
complete: (res) => {
uni.hideLoading();
}
});
} catch (error) {
console.error(error)
}
},
queryDatabase() {
query()
}
}
}
</script>
// \uni-app-x工程目录\uni_modules\lsk-rdb\utssdk\app-harmony\index.uts
import { fileIo as fs } from '@kit.CoreFileKit';
import { relationalStore } from '@kit.ArkData';
export function initDataBaseDir() {
let dirPath = getContext().getApplicationContext().databaseDir + "/entry";
// 创建数据库沙箱目录
try {
if (!fs.accessSync(dirPath)) {
fs.mkdirSync(dirPath);
}
} catch (error) {
console.error('init entry dir err');
}
dirPath = dirPath + '/rdb'
try {
if (!fs.accessSync(dirPath)) {
fs.mkdirSync(dirPath);
}
} catch (error) {
console.error('init rdb dir err');
}
}
export function saveFileToSandbox(path : string) {
initDataBaseDir();
// 数据库名称
let dbName = 'world_cities.mbtiles'
let targetFileUrl = getContext().getApplicationContext().databaseDir + "/entry/rdb/" + dbName;
let file = fs.openSync(path, fs.OpenMode.READ_ONLY)
fs.copyFile(file.fd, targetFileUrl).then(() => {
console.info("Succeeded in copying.");
}).catch((err : any) => {
console.error("Failed in copying.");
console.error(err);
}).finally(() => {
fs.closeSync(file)
})
}
export async function query() {
let store : relationalStore.RdbStore | undefined = undefined;
const STORE_CONFIG : relationalStore.StoreConfig = {
name: 'world_cities.mbtiles',
securityLevel: relationalStore.SecurityLevel.S1
};
store = await relationalStore.getRdbStore(getContext(), STORE_CONFIG);
let predicates = new relationalStore.RdbPredicates("tiles");
let resultSet = await store.query(predicates, ['zoom_level', 'tile_column', 'tile_row', 'tile_data']);
console.info(resultSet.columnNames.join())
// resultSet是一个数据集合的游标,默认指向第-1个记录,有效的数据从0开始。
while (resultSet.goToNextRow()) {
const zoom_level = resultSet.getLong(resultSet.getColumnIndex("zoom_level"));
const tile_column = resultSet.getLong(resultSet.getColumnIndex("tile_column"));
const tile_row = resultSet.getLong(resultSet.getColumnIndex("tile_row"));
const tile_data = resultSet.getBlob(resultSet.getColumnIndex("tile_data"));
console.info(`查询结果:zoom_level=${zoom_level}, tile_column=${tile_column}, tile_row=${tile_row}, tile_data=${tile_data}`);
}
}