QT MySQL数据库连接的最小测试案例

本文介绍QT数据库的最小测试案例,可检验QT是否连接到MySQL数据库。

案例代码一共为xx.pro、widget.h、widget.cpp、main.cpp四个文件,在创建好widget项目文件后,依次将下面的代码拷贝到对应的文件内即可。

pro文件

QT += core gui sql

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

CONFIG += c++11

# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

SOURCES += \
    main.cpp \
    widget.cpp

HEADERS += \
    widget.h

FORMS += \
    widget.ui

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

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QDebug>
#include <QKeyEvent>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private:
    Ui::Widget *ui;
};
#endif // WIDGET_H

widget.cpp

#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setFocusPolicy(Qt::StrongFocus);
}

Widget::~Widget()
{
    delete ui;
}

main.cpp

#include "widget.h"

#include <QApplication>
#include <QSqlDatabase>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    qDebug()<<"drives: ";
	//获取现在可用的数据库驱动
    QStringList drivers = QSqlDatabase::drivers();  
    foreach(QString driver, drivers)
    qDebug() << driver;
    QSqlDatabase database = QSqlDatabase::addDatabase("QMYSQL");
    database.setHostName("127.0.0.1");
    database.setDatabaseName("test");
    database.setUserName("root");
    database.setPassword("1234567890");
    database.setPort(3306);
    if (database.open()) {
            qDebug() << "连接数据库成功";
    } else {
        qDebug() << "连接数据库失败";
    }
//    Widget w;
//    w.show();
    return a.exec();
}

测试

失败示例图
在这里插入图片描述
成功示例图
在这里插入图片描述
出现成功示例图中的结果,说明已经成功配置MySQL的连接,可在程序中使用MySQL相关的数据库操作代码。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值