是否有任何Qt SQLite插件用于通过VFS将数据库存储在RAM中(用于从Qt资源文件加载数据库)? [英] Is there any Qt SQLite plugin for storing database in RAM by VFS (for loading database from Qt resource file)?
问题描述
我在.qrc
中有一些:/test.sqlite3
数据库.目标是在程序中直接使用此数据库.数据库仅用于读取.
I have some :/test.sqlite3
database inside .qrc
. And the goal is to directly use this database in program. Database used only for reading.
QSqlDatabase::setDatabase(":/test.sqlite3")
不起作用,因为Qt SQLite不适用于Qt的文件系统.
QSqlDatabase::setDatabase(":/test.sqlite3")
not works, because Qt SQLite not designed for working with Qt's filesystem.
解决方案之一是将数据库从.qrc
复制到D:\temdb.sqlite3
并由QSqlDatabase::setDatabase("D:\\temdb.sqlite3")
使用.但是程序不能与OS文件系统一起使用.
One of solutions is copying database from .qrc
into D:\temdb.sqlite3
and using it by QSqlDatabase::setDatabase("D:\\temdb.sqlite3")
. But program must not work with OS filesystem.
第二个解决方案是将:/dump.sql
存储在资源中,然后通过QSqlDatabase::setDatabase(":memory:")
创建内存数据库,并通过读取和执行:/dump.sql
行来将转储导入到数据库中.但是这种方法很慢.
Second solution is storing :/dump.sql
in resources, then creating in-memory database by QSqlDatabase::setDatabase(":memory:")
and importing dump into it by reading and executing lines from :/dump.sql
. But this method is slow.
最后,困难但正确的方法是使用VFS
实现为SQLite创建自己的Qt插件,以从RAM中读取数据库,其中的字节数为":/test.sqlite3"
.
And, finally, hard but true way is creating own Qt plugin for SQLite with VFS
implementation for reading database from RAM, where we have bytes of ":/test.sqlite3"
.
还有其他简便的方法吗?
Is there any another easy way?
P.S.我已经阅读了所有问题,例如将内存中的sqlite数据库转换为blob/char数组等,因此请勿将其标记为重复.我的问题是关于其他方法.
P.S. I have already read all questions like Converting in-memory sqlite database to blob/char array and other, so don't mark it as duplicate. My question is about any other methods.
推荐答案
You could take advantage of Qt QTemporaryFile to copy your data and start. QTemporaryfile
works on every os.
这里是一个示例(此临时文件与整个qApp
相关联,以便在退出应用程序后将其删除):
Here is an example (this temporary file is associated to the entire qApp
so that it will be removed once you quit the application):
QTemporaryFile tmpFile(qApp);
tmpFile.setFileTemplate("XXXXXX.sqlite3");
if (tmpFile.open()) {
QString tmp_filename=tmpFile.fileName();
qDebug() << "temporary" << tmp_filename;
QFile file(":/test.sqlite3");
if (file.open(QIODevice::ReadOnly)) {
tmpFile.write(file.readAll());
}
tmpFile.close();
}
您可以将文件tmpFile.fileName()
重新打开为QSqlDatabase
:
The you can reopen the file tmpFile.fileName()
as QSqlDatabase
:
QSqlDatabase::setDatabase(tmpFile.fileName());
这篇关于是否有任何Qt SQLite插件用于通过VFS将数据库存储在RAM中(用于从Qt资源文件加载数据库)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!