2

我有一个使用 QSqlDatabase 在 Qt 中使用 SQLite 的应用程序,如果我在调试模式下编译,一切正常。我的问题是,当我切换到发布模式时,没有任何效果。我的第一个错误似乎与引入 QtCore4.dll 和 QtGui4.dll 文件的代码有关。一旦我将这些文件移动到与编译代码相同的目录中,程序就会加载,但以下错误被写入 Qt Creator 控制台:

QSqlDatabase:未加载 QSQLITE 驱动程序

QSqlDatabase:可用的驱动程序:

QSqlDatabase:加载驱动插件需要一个 QCoreApplication 的实例

我认为这可能来自的唯一一条线是我刚刚在顶部使其全球化的这条线:

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

我的PRO文件如下:

QT       += core gui sql

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = LessonsLearned
TEMPLATE = app


SOURCES += main.cpp\
        lessonslearned.cpp

HEADERS  += lessonslearned.h

FORMS    += lessonslearned.ui

我什至尝试重新安装 Qt 以查看是否可以解决问题。

只是重申......如果我编译调试,一切都很好。问题出现的是版本。

我正在使用 Qt 4.7.3 和 Visual Studio 2008,以防有某种原因可能导致问题。

更新

我已经在类的头文件中移动了“QSqlDatabase db”的声明,并将其设为私有。我还将对 addDatabase("QSQLITE") 的调用移至构造函数:

LessonsLearned::LessonsLearned(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::LessonsLearned)
{
    ui->setupUi(this);

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

这使得需要 QCoreApplication 的错误消失,但我仍然收到前两条消息。仍可在 Debug 中使用,但不能在 Release 中使用。我想知道该程序是否仍然在某个地方指向错误的 DLL。我已经尝试了一些依赖walker,但我还没有找到一个错误的。

UPDATE 2 I found something helpful here: QSQLITE driver not loaded - where to put qt database driver plugins. I think this is the same issue that I had. I still don't know why I had to modify the Release directory to add a sqldrivers folder, but it works.

4

2 回答 2

3

For the release problem:

If bringing QtCode4.dll and QtGui4.dll solved some of the problems then probably bringing the qsqlite4.dll would solve the remaining issue. Just note that you have to put it in a folder named sqldrivers near the executable file.

于 2013-05-16T20:16:14.003 回答
2

Probably your issue is that you have a global variable: QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); That means addDatabase() will get called before main(), which means before the QCoreApplication object is created.

So you can only call addDatabase() after you created your QCoreApplication object (which is usually one of the first things in main()).

Avoid global variables, especially ones with complex types and even more so ones that call functions.

I don't know why you only get the problem in release mode though.

于 2013-05-16T19:50:34.533 回答