Is there any Qt SQLite plugin for storing database in RAM by VFS (for loading database from Qt resource file)?

馋奶兔 提交于 2019-12-01 02:32:54

问题


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") not works, because Qt SQLite not designed for working with Qt's filesystem.

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.

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.

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. 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.


回答1:


You could take advantage of Qt QTemporaryFile to copy your data and start. QTemporaryfile works on every os.

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();
}

The you can reopen the file tmpFile.fileName() as QSqlDatabase:

QSqlDatabase::setDatabase(tmpFile.fileName());


来源:https://stackoverflow.com/questions/40127409/is-there-any-qt-sqlite-plugin-for-storing-database-in-ram-by-vfs-for-loading-da

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!