使用场景:
提示:适用远程连接数据库:
Mac上没有安装数据库,需要Qt6远程连接mysql;
本教程针对arm64,即m系列芯片;
Cmake;
问题描述
目前存在mac资源很少,存在少数的教程,也是存在些许问题;在此经过多次实践,最终记录一下;
解决方案:
提示:没有远程数据库的,使用本地安装的数据库就按部就班走,下面的代码注意修改路径即可;
提示:使用远程数据库,不安装mysql:
第一步
安装mysql-client
,使用brew
brew install mysql-client
第二步
找到mysql-client安装位置:
/opt/homebrew/Cellar/mysql-client
,基本上都会在这个目录下面;
找到这两个路径,后面会用到且关键:
/opt/homebrew/Cellar/mysql-client/8.3.0/include/mysql
/opt/homebrew/Cellar/mysql-client/8.3.0/lib/libmysqlclient.dylib
第三步
打开terminal
cd /Users/username/Qt/6.7.1/Src
./configure -sql-mysql -- -DCMAKE_INCLUDE_PATH="/opt/homebrew/Cellar/mysql-client/8.3.0/include/mysql" -DCMAKE_LIBRARY_PATH="/opt/homebrew/Cellar/mysql-client/8.3.0/lib"
第二行命令的时候会提示错误,可以不用关注;直接next!
cd /Users/username/Qt/6.7.1/macos/plugins/sqldrivers
mkdir build_sqldrivers
cd build_sqldrivers
/Users/username/Qt/6.7.1/macos/bin/qt-cmake -G Ninja /Users/username/Qt/6.7.1/Src/qtbase/src/plugins/sqldrivers -DCMAKE_INSTALL_PREFIX=/Users/username/Qt/6.7.1/macos -DMySQL_INCLUDE_DIR="/opt/homebrew/Cellar/mysql-client/8.3.0/include/mysql" -DMySQL_LIBRARY="/opt/homebrew/Cellar/mysql-client/8.3.0/lib/libmysqlclient.dylib" -DCMAKE_OSX_ARCHITECTURES="arm64"
继续执行以下命令:
sed -i -e 's/-arch x86_64/-arch arm64/g' /Users/username/Qt/6.7.1/macos/plugins/sqldrivers/build_sqldrivers/build.ninja
cmake --build .
cmake --install .
最后一步
找到刚才生成的文件libqsqlmysql.dylib
:
find ~/Qt -name libqsqlmysql.dylib
如果/Users/username/Qt/6.4.2/macos/plugins/sqldrivers
不存在这个文件,复制件过去;
测试
在CmakeLists.txt添加:
find_package(QT NAMES Qt6 Qt5 COMPONENTS Widgets Sql REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Widgets Sql)
target_link_libraries(testIni PRIVATE Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::Sql)
#include "mainwindow.h"
#include <QApplication>
#include <QSqlDatabase>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
qDebug()<<"available drivers:";
QStringList drivers = QSqlDatabase::drivers();
foreach(QString driver, drivers)
qDebug()<<driver;
MainWindow w;
w.show();
return a.exec();
}
如果修改完毕之后仍然没有加载到Qmysql,重启一下Qt Creator
;或者更换一下系统的cmake尝试;