Development environment: Ubuntu18.04+QT5.14.2+MySQL5.7.240
Compilation steps:
1. Install mysql software and driver:
Open the terminal command and execute the installation statement as follows:
sudo apt-get install mysql-server
sudo apt-get install mysql-client sudo apt-get install libmysqlclient-dev
sudo apt-get install libmysql++
2. Query the installed path:
whereis mysql.h
3. How to set access permissions for project files in the QT installation directory
sudo chmod -R 777 /opt/Qt5.14.2/5.14.2/Src/qtbase/src/ plugins/sqldrivers
sudo chmod -R 777 /opt/Qt5.14.2/5.14.2/Src/qtbase/src/plugins/sqldrivers/mysql/mysql.pro
sudo chmod -R 777 /opt/Qt5.14.2/5.14.2/gcc_64
sudo chmod -R 777 /opt/Qt5.14.2/Tools/QtCreator
4. In the terminal command window, enter sudo /opt/Qt5.14.2/Tools/QtCreator/bin/qtcreator and press Enter to open the QtCreator software with administrator privileges.
5. In the QtCreator software, open the mysql project/opt/Qt5.14.2/5.14.2/Src/qtbase/src/plugins/sqldrivers/mysql/mysql.pro project file.
6. Modify the content of the mysql.pro file to
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
include(../qsqldriverbase.pri)
INCLUDEPATH+=/usr/include/mysql
LIBS+=-L/usr/lib/x86_64-linux-gnu/ -lmysqlclient
DESTDIR = ./x86_64-linux-gnu/lib
7. Modify the content of the qsqldriverbase.pri file to
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
8. After compiling and running the mysql.pro project in Release mode, it will be produced in the /opt/Qt5.14.2/5.14.2/Src/qtbase/src/plugins/sqldrivers/mysql/Release/x86_64-linux-gnu/lib directory. Corresponding driver files: libqsqlmysql.so, libqsqlmysql.so.debug. Copy the two driver files to the /opt/Qt5.14.2/5.14.2/gcc_64/plugins/sqldrivers directory.
9. After creating a new test QT project, test the MYSQL database connection. The test code is as follows:
#include <QApplication>
#include <QSqlDatabase>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
// 查看数据库驱动名字
qDebug()<<QSqlDatabase::drivers();
// 加载驱动mysql数据库驱动
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
//本机数据库
db.setHostName("192.168.1.200");
db.setUserName("root");
db.setPassword("123456");
db.setDatabaseName("test");
db.setPort(3306);
if(!db.open())
{
qDebug()<< "服务器连接失败,请稍后重新尝试";
}
else
{
qDebug()<< "服务器连接成功,进行后续数据库增删改查操作";
}
// 关闭数据库
db.close();
return a.exec();
}