主要是对数据库的增删查改的操作
登录/注册界面:
主页面:
添加信息:
删除信息:
删除第一行(支持多行删除)
需求分析:
用QT实现一个学生管理信息系统,数据库为MySQL
要求:
- 1、要求有完整界面,如登录界面、信息操作界面
- 2、要求有数据库
- 3、可以录入学生信息
- 4、可以查询学生信息,支持模糊查询
- 5、可以修改学生信息,支持单个和批量修改
- 6、可以删除学生信息,支持单个和批量删除
- 7、学生信息包括:班级、学号、姓名、性别、出生年月、专业、所属学院
2024.11.30 bug和所需添加记录:
- 注册账号时空值也会新建(已解决)
- 数据库sql语句写在qt上,方便运行(已解决)
- 用户名规则,开头字母
2024.12.6 bug记录
- 相同账号和不同密码,弹出信息框错误(已解决)
- 代码耦合:qt数据库常量抽取出来(已解决)
- 添加信息后没有刷新信息
登录界面:
Login.h
#ifndef LOGIN_H
#define LOGIN_H#include <QWidget>
#include <QSqlDatabase> //数据库驱动
#include <QSqlQuery> //数据库执行语句
#include <QSqlError> //数据库报错
#include <QMessageBox> //消息对话框
#include <QDebug>QT_BEGIN_NAMESPACE
namespace Ui {
class Login;
}
QT_END_NAMESPACEclass Login : public QWidget
{Q_OBJECTpublic:Login(QWidget *parent = nullptr);~Login();void createDataBase();private slots:void on_loginbutton_clicked();void on_registerbtn_clicked();private:Ui::Login *ui;
};
#endif // LOGIN_H
Login.cpp
#include "login.h"
#include "ui_login.h"
#include "homepage.h"
#define databaseName "qt"Login::Login(QWidget *parent): QWidget(parent), ui(new Ui::Login)
{ui->setupUi(this);//加载驱动QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");db.setHostName("127.0.0.1"); // 主机IPdb.setUserName("root"); // 用户名db.setPassword(""); // 密码if (!db.open()) {qDebug() << "WARNING: " << db.lastError().text();return; // 如果连接失败,退出函数}// qDebug() << databaseName;// 检查数据库 qt 是否存在QSqlQuery query;if (!query.exec("CREATE DATABASE IF NOT EXISTS " databaseName)) {qDebug() << "创建数据库" << databaseName << "失败:" << query.lastError().text();return; // 数据库创建失败,退出函数}else{qDebug() << "数据库" << databaseName << "已存在!";}db.setDatabaseName(databaseName); // 现在切换到 qt 数据库if (!db.open()) {qDebug() << "WARNING: 无法打开 " << databaseName << "数据库:" << db.lastError().text();return; // 如果无法连接到 qt,退出函数}// 数据库连接成功,继续后续操作qDebug() << "成功创建数据库!" << databaseName ;createDataBase();
}//sql语句创建数据库
void Login::createDataBase() {// 创建user表的SQL语句QString createUserTable = "CREATE TABLE IF NOT EXISTS `user` (""`account` VARCHAR(20) NOT NULL, ""`pwd` VARCHAR(20) NOT NULL, ""PRIMARY KEY (`account`))";// 创建student表的SQL语句QString createStudentTable = "CREATE TABLE IF NOT EXISTS `student` (""`id` INT(5) NOT NULL, ""`name` VARCHAR(20) NOT NULL, ""`gender` VARCHAR(2) NOT NULL, ""`birthdate` VARCHAR(10) NOT NULL, ""`major` VARCHAR(20) NOT NULL, ""`class` VARCHAR(20) NOT NULL, ""`college` VARCHAR(20) NOT NULL, ""PRIMARY KEY (`id`))";// 执行创建表的SQL语句QSqlQuery query;if (query.exec(createUserTable) && query.exec(createStudentTable)) {qDebug() << "数据库创建成功";} else {qDebug() << "数据库创建失败" << query.lastError().text();}}void Login::on_loginbutton_clicked() //登录功能
{QString account = ui->account->text();QString password = ui->pwd->text();QString sql = QString("select * from user where account='%1' and pwd='%2'").arg(account).arg(password);QSqlQuery query(sql);if(query.next()){QMessageBox::information(this, "登录认证", "登录成功");//登录成功后可以跳转到主页面HomePage *window = new HomePage();window->show();this->close(); //关闭登录窗口}else{QMessageBox::information(this, "登录认证", "登录失败,账户或者密码错误");}// HomePage *window = new HomePage(); //测试专用// window->show();// this->close(); //关闭登录窗口
}void Login::on_registerbtn_clicked() //注册按钮
{QString account = ui->account->text().trimmed();QString password = ui->pwd->text().trimmed();//判断账号和密码是否为空if(account.isEmpty() || password.isEmpty()){QMessageBox::warning(this,"注册认证","账号或密码不能为空!");return; //退出函数}//相同账号,不同密码的情况:QString sql = QString("select * from user where account='%1'").arg(account);QSqlQuery query(sql);if(query.next()){QMessageBox::warning(this,"注册认证","账号已存在!");return; //退出函数}//注册账号sql = QString("insert into user(account,pwd) values('%1','%2');").arg(account).arg(password);if(query.exec(sql)){ //表中存在该账号和密码QMessageBox::information(this,"注册认证","注册失败!");}else{QMessageBox::information(this,"注册认证","注册成功!");}
}Login::~Login()
{delete ui;
}
Login.ui
学生管理信息系统界面:
HomePage.h
#ifndef HOMEPAGE_H
#define HOMEPAGE_H#include <QWidget>
#include <QSqlDatabase> //数据库驱动
#include <QSqlQuery> //数据库执行语句
#include <QSqlError> //数据库报错
#include <QMessageBox> //消息对话框
#include <QDebug>namespace Ui {
class HomePage;
}class HomePage : public QWidget
{Q_OBJECTpublic:explicit HomePage(QWidget *parent = nullptr);~HomePage();void initDatabase(); //加载数据库驱动函数void refreshTable(QString inquiresql); //刷新表格,查询数据库全部内容private slots:void on_refresh_btn_clicked();void on_delete_btn_clicked();void on_inquire_btn_clicked();void on_add_btn_clicked();void on_modify_btn_clicked();private:Ui::HomePage *ui;
};#endif // HOMEPAGE_H
HomePage.cpp
#include "homepage.h"
#include "ui_homepage.h"
#include "add.h"
#include "modify.h"
#define databaseName "qt"HomePage::HomePage(QWidget *parent): QWidget(parent), ui(new Ui::HomePage)
{ui->setupUi(this);initDatabase(); //加载数据库驱动//设置表头QStringList headerList; //定义headerList变量headerList << "选择栏" << "学号" << "姓名" << "性别" << "出生年月" << "专业" << "班级" << "学院"; //添加内容QFont font; //设置字号font.setPointSize(17);ui->tableWidget->setFont(font);ui->tableWidget->setColumnCount(headerList.size()); //设置列数=表头列数ui->tableWidget->setHorizontalHeaderLabels(headerList); //添加headerList到表头ui->tableWidget->setRowCount(3); //设置行数,不设置显示不出文本// 设置列表自动填充满窗口ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);// 设置输入框提示信息为占位符文本,一旦用户开始输入,提示信息会消失。ui->inquire_lineEdit->setPlaceholderText("支持模糊查询,输入姓名或者学号关键词");refreshTable(NULL);
}void HomePage::initDatabase(){ //加载数据库驱动函数QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");db.setHostName("127.0.0.1"); // 主机IPdb.setUserName("root"); // 用户名db.setPassword(""); // 密码db.setDatabaseName(databaseName); // 要连接哪个数据库,它的名字// 打开数据库,如果打不开就弹出报错对话框if(db.open() == false){qDebug() << "WARNING:" << db.lastError().text() << "\n";}// 打开成功qDebug() << "数据库成功打开" << "\n";
}void HomePage::refreshTable(QString inquiresql){//先【从最后往前】删除表格所有行for(int row = ui->tableWidget->rowCount()-1; row >= 0; row--){ui->tableWidget->removeRow(row);}QSqlQuery query;if(inquiresql.isEmpty()){QString sql = "select * from student";query.exec(sql);}else{query.exec(inquiresql);}//数据库查询并添加int row = 0;while(query.next()){int Old_RowCount = ui->tableWidget->rowCount(); //获取当前表格行数ui->tableWidget->setRowCount(Old_RowCount+1); //添加一行//第一列添加复选框QTableWidgetItem *checkbox = new QTableWidgetItem();checkbox->setCheckState(Qt::Unchecked); //设置非选中状态ui->tableWidget->setItem(row, 0, checkbox);//添加数据,未设置只读状态ui->tableWidget->setItem(row, 1, new QTableWidgetItem(query.value(0).toString())); // 学号ui->tableWidget->setItem(row, 2, new QTableWidgetItem(query.value(1).toString())); // 姓名ui->tableWidget->setItem(row, 3, new QTableWidgetItem(query.value(2).toString())); // 性别ui->tableWidget->setItem(row, 4, new QTableWidgetItem(query.value(3).toString())); // 出生年月ui->tableWidget->setItem(row, 5, new QTableWidgetItem(query.value(4).toString())); // 专业ui->tableWidget->setItem(row, 6, new QTableWidgetItem(query.value(5).toString())); // 班级ui->tableWidget->setItem(row, 7, new QTableWidgetItem(query.value(6).toString())); // 学院row++; //下一行}
}void HomePage::on_refresh_btn_clicked() //刷新学生信息
{QString nullString = NULL;refreshTable(nullString); //刷新表格
}void HomePage::on_delete_btn_clicked() //删除学生信息
{QList<QString> StudentId; //存储需要删除的学生id//遍历表格每一行for(int row = ui->tableWidget->rowCount()-1; row >= 0; row--){QTableWidgetItem *checkBoxItem = ui->tableWidget->item(row, 0); //读取勾选框的列表项if(checkBoxItem->checkState() == Qt::Checked){QTableWidgetItem *idItem = ui->tableWidget->item(row, 1); //读取id的列表项if (idItem) {StudentId.append(idItem->text());}}}//没勾选就不删了,退出函数if(StudentId.empty()){QMessageBox::information(this, "提示", "请先勾选需要删除的行");return;}//构建批量删除的SQL语句,参数化查询防止SQL注入QString sql = "DELETE FROM student WHERE id IN (";for (int i = 0; i < StudentId.size(); i++) {sql += "?";if (i < StudentId.size() - 1)sql += ",";}sql += ")";QSqlQuery query;query.prepare(sql);for (int i = 0; i < StudentId.size(); i++) {query.addBindValue(StudentId[i]);}if(query.exec()) {QString nullString = NULL;refreshTable(nullString); //删除成功后立即刷新表格QMessageBox::information(this, "成功", "删除成功!");} else {QMessageBox::information(this, "失败", "删除失败:" + query.lastError().text());}
}void HomePage::on_inquire_btn_clicked() //查询信息
{QString inquireString = ui->inquire_lineEdit->text().trimmed();QString sql = QString("select id, name, gender, birthdate, major, class, college from student where id like \"%1%2\" or name like \"%3%4\"").arg(inquireString, "%", inquireString, "%");refreshTable(sql);
}void HomePage::on_add_btn_clicked() //添加信息
{int Old_RowCount = ui->tableWidget->rowCount(); //获取当前表格行数ui->tableWidget->setRowCount(Old_RowCount+1); //添加一行add *window = new add();window->show();
}void HomePage::on_modify_btn_clicked() //根据学号修改信息
{Modify *window = new Modify();window->show();
}HomePage::~HomePage()
{delete ui;
}
HomePage.ui
添加信息界面:
add.h
#ifndef ADD_H
#define ADD_H#include <QWidget>
#include <QMessageBox> //消息对话框
#include <QDebug>
#include <QSqlDatabase> //数据库驱动
#include <QSqlQuery> //数据库执行语句
#include <QSqlError> //数据库报错namespace Ui {
class add;
}class add : public QWidget
{Q_OBJECTpublic:explicit add(QWidget *parent = nullptr);~add();private slots:void on_add_btn_clicked();private:Ui::add *ui;
};#endif // ADD_H
add.cpp
#include "add.h"
#include "ui_add.h"
#include "homepage.h"add::add(QWidget *parent): QWidget(parent), ui(new Ui::add)
{ui->setupUi(this);
}void add::on_add_btn_clicked()
{QString id = ui->id_linedit->text().trimmed();QString name = ui->name_lineEdit->text().trimmed();QString gender = ui->gender_lineEdit->text().trimmed();QString birthdate = ui->birth_lineEdit->text().trimmed();QString major = ui->major_lineEdit->text().trimmed();QString Class = ui->class_lineEdit->text().trimmed();QString college = ui->college_lineEdit->text().trimmed();//结束条件if(id.isEmpty() || name.isEmpty() || gender.isEmpty()|| birthdate.isEmpty() || major.isEmpty() || Class.isEmpty() || college.isEmpty()){QMessageBox::warning(this, "警告", "信息请填写完整!");return;}//判断学号是否存在,存在则结束QString sql = "select * from student where id = ?";QSqlQuery query;query.prepare(sql);query.bindValue("?", id);query.exec();if(query.next()){QMessageBox::warning(this, "警告", "学号已存在!");return;}//添加学生sql = QString("insert into student (id, name, gender, birthdate, major, class, college) values (\"%1\", \"%2\", \"%3\", \"%4\", \"%5\", \"%6\", \"%7\")").arg(id, name, gender, birthdate, major, Class, college);if(query.exec(sql)) {QMessageBox::information(this, "成功", "插入成功!");close(); //关闭窗口HomePage *homepage = new HomePage();homepage->refreshTable(NULL); //刷新表格}else {QMessageBox::information(this, "失败", "插入失败:" + query.lastError().text());}
}add::~add()
{delete ui;
}
add.ui
修改信息界面:
Modify.h
#ifndef MODIFY_H
#define MODIFY_H#include <QWidget>
#include <QMessageBox> //消息对话框
#include <QDebug>
#include <QSqlDatabase> //数据库驱动
#include <QSqlQuery> //数据库执行语句
#include <QSqlError> //数据库报错namespace Ui {
class Modify;
}class Modify : public QWidget
{Q_OBJECTpublic:explicit Modify(QWidget *parent = nullptr);~Modify();private slots:void on_modify_btn_clicked();private:Ui::Modify *ui;
};#endif // MODIFY_H
Modify.cpp
#include "modify.h"
#include "ui_modify.h"
#include "homepage.h"Modify::Modify(QWidget *parent): QWidget(parent), ui(new Ui::Modify)
{ui->setupUi(this);
}void Modify::on_modify_btn_clicked()
{QString id = ui->id_linedit->text().trimmed();QString name = ui->name_lineEdit->text().trimmed();QString gender = ui->gender_lineEdit->text().trimmed();QString birthdate = ui->birth_lineEdit->text().trimmed();QString major = ui->major_lineEdit->text().trimmed();QString Class = ui->class_lineEdit->text().trimmed();QString college = ui->college_lineEdit->text().trimmed();if(id.isEmpty() || name.isEmpty() || gender.isEmpty()|| birthdate.isEmpty() || major.isEmpty() || Class.isEmpty() || college.isEmpty()){QMessageBox::warning(this, "警告", "信息请填写完整!");return;}QSqlQuery query;QString sql = QString("update student set name = \"%1\"," "gender =\"%2\", birthdate =\"%3\", major = \"%4\", ""Class = \"%5\", college = \"%6\" where id =%7").arg(name, gender, birthdate, major, Class, college, id);if(query.exec(sql)){QMessageBox::information(this, "成功", "修改成功!");HomePage *homepage = new HomePage();QString nullString = NULL;homepage->refreshTable(nullString); //刷新表格close(); //关闭窗口}else{QMessageBox::information(this, "失败", "修改失败!");}
}Modify::~Modify()
{delete ui;
}
Modify.ui
参考资料:
【C++】C++ QT实现 学生信息管理系统(QT源码)【独一无二】_qt学生管理系统-CSDN博客
如何用qt实现学生信息管理系统_用qtcreater做一个学生信息管理系统-CSDN博客
Qt 学习第十一天:QTableWidget 的使用_qt tablewidget resize-CSDN博客
Qt 学习第十一天:QTableWidget 的使用_qt tablewidget resize-CSDN博客
Qt设计精美的登录注册界面(包含SQLite数据库应用)_qt登录界面设计-CSDN博客