QT5.14.2测试mysql数据库是否配置成功(新手)

1.先配置数据库:

QT5.14.2配置数据库教程:
https://blog.csdn.net/destiny_balabala/article/details/108183046

2.新建项目

教程:https://blog.csdn.net/qq_36926037/article/details/123720153

需要新建:

在这里插入图片描述
其中内容为:
①.pro:

QT += core gui sql  # 添加 sql 模块

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Please consult the documentation of the
# deprecated API in order to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS

TARGET = testMysql
TEMPLATE = app

# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    database.cpp \
    main.cpp \
    mainwindow.cpp

HEADERS += \
    database.h \
    mainwindow.h

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

②database.h:

#ifndef DATABASE_H
#define DATABASE_H

#include <QSqlDatabase>
#include <QMessageBox>
#include <QDebug>
#include <QSqlError>

bool createConnection();

#endif // DATABASE_H

③database.cpp(注意替换)

#include "database.h"

bool createConnection()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setPort(3306);
    db.setDatabaseName("name");// 替换为你的数据库名字
    db.setUserName("root");
    db.setPassword("123456"); // 替换为你的实际密码

    if (!db.open())
    {
        QMessageBox::critical(0, "Cannot open database",
                              "Unable to establish a database connection.", QMessageBox::Cancel);
        qDebug() << db.lastError().text();
        return false;
    }
    else
    {
        QMessageBox::information(0, "Successfully", "Establish a database connection", QMessageBox::Ok);
    }
    return true;
}

④main.cpp(用于执行)

#include "mainwindow.h"
#include "database.h" // 确保包含 database.h 头文件
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    if (createConnection())
       {
           w.show();
           return a.exec();
       }
       else
       {
           return -1;
       }
}




3.如果执行main后弹出来Successfully establish a database connection",那么说明数据库连接成功了。

ps:记得编译(刚开始用这个软件,还不知道编译是不是真的影响执行,小菜鸡晚点了解了来补全

在这里插入图片描述

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值