0

I'm trying to implement a single QSqlDatabase instance for all instances of my class.

#include <QCoreApplication>
#include <QtSql/QSqlDatabase>

class MyClass
{
    static QSqlDatabase db;
};

QSqlDatabase MyClass::db = QSqlDatabase::addDatabase("QSQLITE");

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    return a.exec();
}

But this code doesn't seems to work in Release mode:

QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins

Screen (error)
I've used windeployqt.exe to build independent Release version.

In Debug this works because sqldriver loaded directly from Qt directory. When i'm trying to put it to release it makes no sense.

Joe Dea
  • 29
  • 2
  • 7
  • For me (Arch Linux, Qt 5.12.0, sqlite 3.26.0), your code works fine. Did you build the Qt sqlite plugin (https://doc.qt.io/qt-5/sql-driver.html#qsqlite)? – taminob Feb 08 '19 at 20:23
  • Do not run this code in Qt. Run exe file directly. – Joe Dea Feb 08 '19 at 20:34
  • If that's the case, I guess you're missing some dynamic linked libraries. Test your dependencies using DependencyWalker and copy the needed dlls into the directory of your executable. After that, try it again. – taminob Feb 08 '19 at 20:53

1 Answers1

0

QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins

So you're not allowed to load sql plugins on the global level. Just don't try to make it "static inside class", but make it "static inside static method", like in a typical singleton pattern. Sort of,

class MyClass
{
    static QSqlDatabase& get_db();
};

QSqlDatabase& MyClass::get_db()
{
    static QSqlDatabase db;
    if (!db.isValid())
        db = QSqlDatabase::addDatabase("QSQLITE");
    return db;
}
Matt
  • 13,674
  • 1
  • 18
  • 27