1、安装mysql,workbench,为mysql添加环境变量
2、安装Qt带src,然后到如下目录,找到mysql.pro(建议做个副本先)
http://D:\Qt\Qt5.13.2\5.13.2\Src\qtbase\src\plugins\sqldrivers\mysql
mysql.pro
注意路径的 \ / 和双引号的使用,搞不定就照抄
TARGET = qsqlmysqlHEADERS += $$PWD/qsql_mysql_p.h
SOURCES += $$PWD/qsql_mysql.cpp $$PWD/main.cpp#注释掉
#QMAKE_USE += mysqlOTHER_FILES += mysql.jsonPLUGIN_CLASS_NAME = QMYSQLDriverPlugininclude(../qsqldriverbase.pri)#这个主要是添加.h依赖文件使用
INCLUDEPATH+="C:/Program Files/MySQL/MySQL Server 8.0/include"#添加依赖的.lib文件
LIBS+="C:/Program Files/MySQL/MySQL Server 8.0/lib/libmysql.lib"#生成你所需要的dll存放目录
DESTDIR="D:/MYSQL/lib"#路径换成自己的mysql路径
qsqldriverbase.pri
QT = core core-private sql-private# For QMAKE_USE in the parent projects.
#include($$shadowed($$PWD)/qtsqldrivers-config.pri)
#include(./qsqldriverbase.pri)
include(./configure.pri)PLUGIN_TYPE = sqldrivers
load(qt_plugin)DEFINES += QT_NO_CAST_TO_ASCII QT_NO_CAST_FROM_ASCII
3、编译得到两个dll,
由于在mysql.pro中已经定义目标目录,DESTDIR="D:/MYSQL/lib"
复制到
D:\Qt\Qt5.13.2\5.13.2\mingw73_64\plugins\sqldrivers
4、 打开mysql安装目录下lib目录
复制libmysql.dll到Qt如下bin目录
5、WorkBench创建database和table,Qt项目写代码如下
void Mysql::on_ConnectButton_clicked()
{db = QSqlDatabase::addDatabase("QMYSQL");db.setHostName("127.0.0.1");db.setPort(3306);db.setDatabaseName("jetring");db.setUserName("root");db.setPassword("123456");if(db.open()){ui->textEdit->append("Mysql connect success!");}else{ui->textEdit->append("Mysql connect failed.");ui->textEdit->append("Error: " + db.lastError().text());}
}
连接成功!
PS:我的版本
感谢如下文章作者:
https://www.cnblogs.com/lpxblog/p/6698255.html