文章目录
- 0 背景
- 1 编译过程
- 2 福利
0 背景
因为需要连接到mysql数据库,所以需要连mysql驱动。
1 编译过程
1,打开文件/Users/mac/Qt5.14.2/5.14.2/Src/qtbase/src/plugins/sqldrivers/sqldrivers.pro
,注释掉QMAKE_USE += mysql
;
如果出现如下错误(Cannot read /qtsqldrivers-config.pri: No such file or directory
):
Info: creating stash file /Users/fjl/Qt/5.15.2/Src/qtbase/src/plugins/sqldrivers/.qmake.stash
Cannot read /qtsqldrivers-config.pri: No such file or directory
/Users/fjl/Qt/5.15.2/clang_64/mkspecs/features/qt_plugin.prf:59: Cannot write file /mkspecs/modules-inst/qt_plugin_qsqlmysql.pri: Cannot create parent directory
09:46:44: 进程"/Users/fjl/Qt/5.15.2/clang_64/bin/qmake"退出,退出代码 3 。
Error while building/deploying project mysql (kit: Desktop Qt 5.15.2 clang 64bit)
When executing step "qmake"
修改下面两个文件
/Users/mac/Qt5.15/5.15.2/clang_64/mkspecs/features/qt_plugin.prf
,/Users/mac/Qt5.15/5.15.2/Src/qtbase/mkspecs/features/qt_plugin.prf
,修改方法相同,把注释的内容修改为下面一行的内容(注意路径替换为自己的本地路径):
# DESTDIR = $$MODULE_BASE_OUTDIR/plugins/$$PLUGIN_TYPE
DESTDIR = /Users/mac/Qt5.15/5.15.2/Src/qtbase/plugins/$$PLUGIN_TYPECONFIG(static, static|shared)|prefix_build {
# mod_work_pfx = $$MODULE_QMAKE_OUTDIR/mkspecs/modulesmod_work_pfx = /Users/mac/Qt5.15/5.15.2/Src/qtbase/mkspecs/modulesforce_independent: \
# mod_inst_pfx = $$MODULE_QMAKE_OUTDIR/mkspecs/modules-inst
2,添加mysql的外部关联库;
mac如下:
macx: LIBS += -L$$PWD/../../../../../../../../../../usr/local/Cellar/mysql@5.7/5.7.44_1/lib/ -lmysqlclient.20INCLUDEPATH += $$PWD/../../../../../../../../../../usr/local/Cellar/mysql@5.7/5.7.44_1/include/mysqlDEPENDPATH += $$PWD/../../../../../../../../../../usr/local/Cellar/mysql@5.7/5.7.44_1/include/mysql
3,编译文件,得到mysql驱动;
4,把编译好的mysql放入到如下文件夹sqldrivers
中,把mysql的库文件也放入到bin
;
5,运行测试程序。
#include "mainwindow.h"#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>int main(int argc, char *argv[])
{QApplication a(argc, argv);// MainWindow w;// w.show();qDebug()<<"查看目前可用驱动";QStringList drivers = QSqlDatabase::drivers();for(auto driver: drivers){qDebug()<<driver<<" ";}//设置数据库驱动QSqlDatabase db1 = QSqlDatabase::addDatabase("QMYSQL", "connection1");db1.setHostName("192.168.0.104");db1.setUserName("root");db1.setPassword("password");db1.setPort(3309);db1.setDatabaseName("test_db");if(db1.open()){qDebug()<<"数据库打开成功";}return a.exec();}
2 福利
编译好的mysql驱动,含windows和mac版本的(5.14.2,5.15.2,6.5.3),链接如下:
链接:https://pan.baidu.com/s/1m15DbFuFTtXfEyqyOS2cew
提取码: 2o2s