如何确定 SQLite 文件在 QML LocalStorage 中的存储位置

How to decide where the SQLite file is stored in QML LocalStorage

本文关键字:存储 位置 LocalStorage QML 何确定 SQLite 文件      更新时间:2023-10-16

我有这个代码:

import QtQuick 2.6
import QtQuick.Controls 2.1
import QtQuick.LocalStorage 2.0
ApplicationWindow {
visible: true
width: 640
height: 480
title: qsTr("Hello World")
property var db // the database of this application
property string dbIdentifier: '/Users/cedo/desktop/test/DatabaseApplicationDB.db'
property string dbVersion: '1.0'
property string dbDescription: 'DatabaseApplicationDB'
property int dbEstimatedSize: 1000000
Component.onCompleted: {
db = LocalStorage.openDatabaseSync(dbIdentifier, dbVersion, dbDescription, dbEstimatedSize);
db.transaction(function(tx) {
var sql = "create table if not exists mytable(id integer)";
tx.executeSql(sql);
});
}
}

dbIdentifier在创建数据库时起作用,但是当我在桌面中搜索db文件时,该文件不存在。它在哪里?或者如何决定把它放在哪里?

根据openDatabaseSync()方法文档,函数原型为:

object openDatabaseSync(string name, string version, string description, int estimated_size, jsobject callback(db))
名称

是数据库名称

版本是数据库版本

说明是数据库显示名称

estimated_size是数据库的估计大小(以字节为单位)

回调是一个可选参数,如果尚未创建数据库,则调用该参数。

所以没有文件名参数。同样,根据文档:

这些数据库是特定于用户和特定于 QML 的,但所有 QML 应用程序都可以访问。它们存储在 QQmlEngine::offlineStoragePath() 的 Databases 子目录中,目前作为 SQLite 数据库。

为了能够将数据库文件放入某个自定义目录中,您应该使用QQmlEngine 或 QQmlApplicationEngine实例的setOfflineStoragePath(const QString &dir)函数。

若要查看数据库文件当前所在的位置,请使用以下C++代码:

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
qDebug() << engine.offlineStoragePath();

更多信息在这里和这里

在 Linux 上,它是.local/share/*project_name*/QML/OfflineStorage/Databases