Tag Archives: QMYSQL driver not loaded

Solving the problem of QT connecting MySQL database in Windows system: qmmysql driver not loaded

In the process of learning QT, we encountered the situation that we could not connect to the database

#include <QApplication>
#include <QtSql>
#include <QMessageBox>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

 //Show existing database driver
    qDebug()<<QSqlDatabase::drivers();

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("dbname");
    db.setUserName("root");
    db.setPassword("password");
    
    if (!db.open()) {
       QMessageBox::critical(0, QObject::tr("Database Error"),
                              db.lastError().text());
    }

    return a.exec();
}

The output of the console is:

As shown above, MySQL driver exists, but it still prompts an error: qmmysql driver not loaded

The reason is that libmysql.dll is missing in the program

This dynamic connection library is in the Lib directory of the MySQL installation file. For example, if my MySQL is installed on Disk C, libmysql.dll is located at:

C:\MySQL\MySQL Server 5.7\lib\

Find libmysql.dll, copy it to the directory where your exe is located, and then run the program. At this time, you can connect to MySQL

note: 32-bit QT program must use 32-bit libmysql.dll, not 64 bit. Similarly, 64 bit programs use 64 bit libmysql. DLL

Libmysql.dll can be found in the Lib directory of the MySQL installation file

If there is no corresponding version, you can also download it here:

Connection: http://pan.baidu.com/s/1kVKwLuR

Password: v6uy

You can connect to the database through the above method, but it is very troublesome to copy libmysql.dll to the directory where the EXE is located every time. Therefore, when writing programs, you can use a convenient method:

Copy libmysql.dll to the bin directory of QT installation file, such as my bin directory:

D:\Qt\Qt5.7.0\5.7\mingw53_32\bin\

After copying to the bin directory, there is no need to copy libmysql.dll to the directory where the EXE is located. The program can connect to the MySQL database correctly