QSqlDatabase: QMYSQL driver not loaded
QSqlDatabase: available drivers: QSQLITE QODBC QODBC3 QPSQL QPSQL7
系统环境:
数据库: mysql-5.7.33-winx64,安装目录:D:\Workspace\UDE\mysql\mysql-5.7.33-winx64
Qt:Qt5.12.10,安装目录:D:\Workspace\UDE\Qt\Qt5.12.10\5.12.10
解决方案编译环境
基于Desktop Qt 5.12.10 MinGW 64-bit
MySQL驱动源码目录:D:\Workspace\UDE\Qt\Qt5.12.10\5.12.10\Src\qtbase\src\plugins\sqldrivers\mysql
修改mysql.pro
TARGET = qsqlmysql
HEADERS += $$PWD/qsql_mysql_p.h
SOURCES += $$PWD/qsql_mysql.cpp $$PWD/main.cpp
#QMAKE_USE += mysql
OTHER_FILES += mysql.json
PLUGIN_CLASS_NAME = QMYSQLDriverPlugin
LIBS += "D:\Workspace\UDE\mysql\mysql-5.7.33-winx64\lib\libmysql.lib"
INCLUDEPATH += "D:\Workspace\UDE\mysql\mysql-5.7.33-winx64\include"
DEPENDPATH += "D:\Workspace\UDE\mysql\mysql-5.7.33-winx64\include"
include(../qsqldriverbase.pri)
修改qsqldriverbase.pri
QT = core core-private sql-private
# For QMAKE_USE in the parent projects.
#include($$shadowed($$PWD)/qtsqldrivers-config.pri)
include(./configure.pri)
PLUGIN_TYPE = sqldrivers
load(qt_plugin)
DEFINES += QT_NO_CAST_TO_ASCII QT_NO_CAST_FROM_ASCII
编译生成
libqsqlmysql.a
libqsqlmysqld.a
qsqlmysql.dll
qsqlmysqld.dll
将这4个文件拷贝至目录:D:\Workspace\UDE\Qt\Qt5.12.10\5.12.10\mingw73_64\plugins\sqldrivers
拷贝MySQL库文件
libmysql.dll
libmysql.lib
libmysqld.dll
libmysqld.lib
将这4个文件拷贝至目录:D:\Workspace\UDE\Qt\Qt5.12.10\5.12.10\mingw73_64\bin
测试结果qDebug() << QSqlDatabase::drivers();
// 添加MySQL数据库
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
// 连接数据库
db.setHostName("127.0.0.1"); // 数据库服务器IP
db.setUserName("root"); // 数据库用户名
db.setPassword("123456"); // 密码
db.setDatabaseName("info"); // 使用哪个数据库
// 打开数据库
if( !db.open() ) // 数据库打开失败
{
QMessageBox::warning(this, "错误", db.lastError().text());
return;
}
("QSQLITE", "QMYSQL", "QMYSQL3", "QODBC", "QODBC3", "QPSQL", "QPSQL7")