Ubuntu 18.04.5 LTS 编译Qt5.14.2 mysql 驱动
1、mysql版本为系统安装的默认版本
mysql -V
2、查看mysql.h文件所在位置
whereis mysql
locate mysql.h
3、查找 libmysqlclient.so 所在路径
locate libmysqlclient.so
4、定位到qt源码目录下mysql驱动的编译路径
导航到本主机的安装路径:
cd /opt/Qt5.14.2/5.14.2/Src/qtbase/src/plugins/sqldrivers/mysql/
修改mysql.pro文件,添加我们刚才找到的mysql相关的 头文件路径 和 链接库路径,修改后的文件如下:
TARGET = qsqlmysql
HEADERS += $$PWD/qsql_mysql_p.h
SOURCES += $$PWD/qsql_mysql.cpp $$PWD/main.cpp
#QMAKE_USE += mysql
OTHER_FILES += mysql.json
INCLUDEPATH += /usr/include/mysql
LIBS += -L/usr/lib/x86_64-linux-gnu -lmysqlclient
PLUGIN_CLASS_NAME = QMYSQLDriverPlugin
include(../qsqldriverbase.pri)
5、接下来执行以下命令进行编译mysql驱动
cd ..
sudo /opt/Qt5.14.2/5.14.2/gcc_64/bin/qmake
cd mysql/
sudo /opt/Qt5.14.2/5.14.2/gcc_64/bin/qmake
sudo make
编译安装完成后如下图:
从图中我我们可以看到编译好的文件位于 …/…/…/…/plugins/sqldrivers/libqsqlmysql.so 目录下
接下来把这几个编译生成的文件拷贝到合适的目录下,如下图:
这样编译mysql驱动就完成了
测试程序
qDebug() << QSqlDatabase::drivers();
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setUserName("root");
db.setPassword("1234");
db.setPort(3306);
db.setDatabaseName("mysql");
qDebug() << (db.open() ? "open db success." : "open db failed.");
QSqlQuery cursor;
QString query = " SELECT user, host FROM user; ";
if (cursor.exec(query)) {
while (cursor.next()) {
qDebug() << "user: " << cursor.value("user").toString()
<< "host: " << cursor.value("host").toString();
}
}
输出结果
("QSQLITE", "QMYSQL", "QMYSQL3", "QODBC", "QODBC3", "QPSQL", "QPSQL7")
open db success.
user: "root" host: "%"
user: "debian-sys-maint" host: "localhost"
user: "mysql.session" host: "localhost"
user: "mysql.sys" host: "localhost"
user: "root" host: "localhost"