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;
}
}