Qt connects to MySQL database (nanny level success version tutorial)

one,

The VIP channel can follow me, private message me, directly send two dynamic libraries, and take off directly.

1. Check sources when installing Qt
Check mingw and sources

2. Configure the path environment variable
① This computer->Properties->Advanced system settings->Environment variables
insert image description here
② Double-click the path->Create new in the upper right corner
insert image description here

③ Add these two paths, and finally confirm

3. Compile the mysql driver (open the mysql.pro file in Qt)
1) Find the mysql.pro file in this path D:\QT5.14.2\5.14.2\Src\qtbase\src\plugins\sqldrivers\mysql
insert image description here

Double-click the mysql.pro file

2) Copy this string of code

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
# !!你安装的mysql的lib路径
LIBS += -L $$quote(C:/Program Files/MySQL/MySQL Server 8.0/lib) -llibmysql
# !!你安装的mysql的include路径
INCLUDEPATH += $$quote(C:/Program Files/MySQL/MySQL Server 8.0/include)
# !!你安装的mysql的include路径
DEPENDPATH += $$quote(C:/Program Files/MySQL/MySQL Server 8.0/include)


include(../qsqldriverbase.pri)

insert image description here
insert image description here

3) Replace the path corresponding to mysql, and then compile it
insert image description here

After compiling, we can find a plugins folder in the same directory of Qt
insert image description here

Double-click plugins, we find qsqlmysql.dll

4. Copy the dynamic library
(1) Copy the generated qsqlmysql.dll to the sqldrivers of mingw
and put it under this directory D:\QT5.14.2\5.14.2\mingw73_64\plugins\sqldrivers
insert image description here

(2) Copy the dynamic library mysql.dll of mysql to the bin of mingw
insert image description here

In this way, the configuration of our Qt connection to MySQL is complete!

Second, the next step is to enter Qt

1. In the pro file + sql
insert image description here
2. Add the header file
insert image description here
3. Enter the code (provided that you have created a data name in advance).
insert image description here

QSqlDatabase db=QSqlDatabase::addDatabase("QMYSQL");//添加驱动
    db.setHostName("127.0.0.1");//ip地址
    db.setDatabaseName("stu");//数据库名
    db.setUserName("root");//用户名
    db.setPassword("123456");//密码

    if (db.open())
    {
    
    
        qDebug()<<"open successful";  //如果连接成功打印 open successful

    }
    else
    {
    
    
        qDebug()<<"error"; //连接失败打印error
    }

If you can get here, then OK, congratulations on your success!

Guess you like

Origin blog.csdn.net/weixin_45920624/article/details/129677250