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
Similar Posts:
- How to Solve QSqlDatabase Error: QMYSQL driver not loaded
- Error: Failed to connect database.Driver not loaded Driver not loaded
- [Solved] SQLyog Connect MYSQL Error: 2058 plugin caching_sha2_password could not be loaded
- MySQL 5.7 installation, mysql. Plugin ‘doesn’t exist error resolution
- MySQL Connect Error: Authentication plugin ‘caching_sha2_password’ cannot be loaded
- Laravel [1045] Solution Access denied for user’homestead’@’localhost’
- java.sql.SQLException: Unable to load authentication plugin ‘caching_sha2_password‘
- [Solved] Deploying Tomcat connection in Linux Navicat reports error 2059 – authentication plugin ‘caching_sha2_Password ‘cannot be loaded: + Xi input 9 g
- CentOS7 MYSQL Connect Error: [ERROR] InnoDB: The innodb_system data file ‘ibdata1’ must be writable
- [Solved] MySql Host is blocked because of many connection errors; unblock with ‘mysqladmin flush-hosts…