Qt——连接mysql增删查改(仓库管理极简版)

目录

UI布局设计

.pro文件

mainwindow.h

main.cpp


UI布局设计

.pro文件

QT       += core gui
QT       += core gui sql
QT       += 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

# 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 += \
    main.cpp \
    mainwindow.cpp

HEADERS += \
    mainwindow.h

FORMS += \
    mainwindow.ui

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

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QMessageBox>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlQuery>
#include <QDebug>
#include <QtSql/QSqlQueryModel>

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void ReshowTable_goods();
    void ReshowTable_people();
    void on_move_goods_clicked();

    void on_move_people_clicked();


   void on_pushButton_addgoods_clicked();

   void on_pushButton_selectgoods_clicked();

   void on_pushButton_changegoods_clicked();

   void on_pushButton_deletegoods_clicked();


   void on_pushButton_addpeople_clicked();

   void on_pushButton_selectpeople_clicked();

   void on_pushButton_changepeople_clicked();

   void on_pushButton_deletepeople_clicked();

private:
    Ui::MainWindow *ui;

    QSqlDatabase db= QSqlDatabase::addDatabase("QMYSQL");

    QSqlQueryModel *goodsMode;//货物数据模型
    QSqlQueryModel *peopleMode;//工作人员数据模型

};
#endif // MAINWINDOW_H

main.cpp

#include "mainwindow.h"

#include <QApplication>

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

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
void sqlconnect(QWidget* parent);
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    goodsMode = new QSqlQueryModel(ui->tableView_goods);
     peopleMode = new QSqlQueryModel(ui->tableView_people);//绑定
    sqlconnect(this);

}

void sqlconnect(QWidget* parent)
{


    //连接数据库
      QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
      db.setHostName("127.0.0.1");
      db.setPort(3306);

      db.setDatabaseName("sqlconnect");//数据库名称
      db.setUserName("root");//用户名
      db.setPassword("");//密码



      qDebug()<<"available drivers:";
      QStringList drivers = QSqlDatabase::drivers();
      for(auto driver: drivers)
          qDebug() << driver;
      bool ok = db.open();
      if(ok==0)
      {
          QMessageBox::information(parent, "提示","数据库连接失败");
          parent->close();
          qDebug()<<"数据库连接失败";
      }

      //若数据库中没有表,则新建
      QSqlQuery query;

      QString createTableGoods="create table if not exists goods(id int primary key auto_increment,name varchar(10),number int, price varchar(10), data varchar(15),server varchar(10),endline int,code varchar(15));";
      QString createTableWoker="create table if not exists woker(name varchar(10),phonenumber varchar(20), sex varchar(8), age int);";
      query.exec(createTableGoods);
      query.exec(createTableWoker);
}

MainWindow::~MainWindow()
{
    delete ui;
}
//___________________________________________________________________________________________________________
void MainWindow::ReshowTable_goods()
{
    goodsMode->setHeaderData(0,Qt::Horizontal,tr("入库编号"));
    goodsMode->setHeaderData(1,Qt::Horizontal,tr("名称"));
    goodsMode->setHeaderData(2,Qt::Horizontal,tr("数量"));
    goodsMode->setHeaderData(3,Qt::Horizontal,tr("单价"));
    goodsMode->setHeaderData(4,Qt::Horizontal,tr("生产日期"));
    goodsMode->setHeaderData(5,Qt::Horizontal,tr("供应商"));
    goodsMode->setHeaderData(6,Qt::Horizontal,tr("保质期"));
    goodsMode->setHeaderData(7,Qt::Horizontal,tr("条形码编号"));
    ui->tableView_goods->setModel(goodsMode);
}

void MainWindow::on_move_goods_clicked()
{
    ui->stackedWidget->setCurrentIndex(0);
}

void MainWindow::on_move_people_clicked()
{
     ui->stackedWidget->setCurrentIndex(1);
}

void MainWindow::on_pushButton_addgoods_clicked()
{
    QString id = ui->lineEdit_goods_id->text();
    QString name = ui->lineEdit_goods_name->text();
    QString number = ui->lineEdit_goods_number->text();
    QString price = ui->lineEdit_goods_price->text();
    QString data = ui->lineEdit_goods_data->text();
    QString server = ui->lineEdit_goods_server->text();
    QString endline = ui->lineEdit_goods_endline->text();
    QString code = ui->lineEdit_goods_code->text();

    QSqlQuery query;
    QString str1 = "" + id +",'"+ name +"'," + number + ",'" +price+"','"+data+"','" +server+"',"+endline+",'"+ code+"'";
    QString str = "insert into goods(id,name,number,price,data,server,endline,code) values("+ str1 +");";


    bool success = query.exec(str);
    if(success)
    {
        QMessageBox::information(this, "提示","入库成功");
    }
    else
    {
         QMessageBox::information(this, "提示","入库失败,请检查输入的数据是否正确");
    }
    goodsMode->setQuery("select * from goods;");
    ReshowTable_goods();
}


void MainWindow::on_pushButton_selectgoods_clicked()
{
    goodsMode->setQuery("select * from goods;");
    ReshowTable_goods();
}

void MainWindow::on_pushButton_changegoods_clicked()
{
    QSqlQuery query;
    QString str = "update goods set id = '"+ ui->lineEdit_goods_id->text() + "', name='" + ui->lineEdit_goods_name->text()
            + "',number='" + ui->lineEdit_goods_number->text() + "',price='" + ui->lineEdit_goods_price->text()
            + "',server='" + ui->lineEdit_goods_server->text()+ "',data='" + ui->lineEdit_goods_data->text()
            + "',code='" + ui->lineEdit_goods_code->text()+ "',endline='" + ui->lineEdit_goods_endline->text()
            + "' where number='" + ui->lineEdit_goods_id->text() + "';";
    query.exec(str);
    QMessageBox::information(this, "修改成功", "表信息修改成功");
    goodsMode->setQuery("select * from goods;");
    ReshowTable_goods();
}

void MainWindow::on_pushButton_deletegoods_clicked()
{
    QSqlQuery query;
    int currentrow = ui->tableView_goods->currentIndex().row();
    goodsMode->removeRow(currentrow);
    if(currentrow != -1)//若选中一行
    {
        int ok  =  QMessageBox::warning(this,tr("删除当前行!"),tr("你确定删除当前行吗?"), QMessageBox::Yes,QMessageBox::No);
        //如确认删除
        if(ok == QMessageBox::Yes)
        {
            goodsMode->removeRow(currentrow);
            QString id = goodsMode->data(goodsMode->index(currentrow,0)).toString();//获取id
            QString del = "delete from goods where id='" + id + "';";
            query.exec(del);
            goodsMode->setQuery("select * from goods");
            ui->tableView_goods->setModel(goodsMode);
            QMessageBox::information(this, "删除成功", "所选信息删除成功");
        }
    }
    else
        QMessageBox::information(this, "提示", "请选择你要删除的信息行");
}

//__________________________________________________________________________________________________________________
void MainWindow::ReshowTable_people()
{
    peopleMode->setHeaderData(0,Qt::Horizontal,tr("姓名"));
    peopleMode->setHeaderData(1,Qt::Horizontal,tr("性别"));
    peopleMode->setHeaderData(2,Qt::Horizontal,tr("年龄"));
    peopleMode->setHeaderData(3,Qt::Horizontal,tr("电话"));
    ui->tableView_people->setModel(peopleMode);


}
void MainWindow::on_pushButton_addpeople_clicked()
{
    QString name = ui->lineEdit_people_name->text();
    QString sex = ui->lineEdit_people_sex->text();
    QString age = ui->lineEdit_people_age->text();
    QString phonenumber = ui->lineEdit_people_phonenumber->text();

    QSqlQuery query;
    QString str1 = "'" + name +"','"+ phonenumber +"','" + sex + "'," +age+"";
    QString str = "insert into woker(name,phonenumber,sex,age) values("+ str1 +");";

    bool success = query.exec(str);
    if(success)
    {
        QMessageBox::information(this, "提示","增加成功");
    }
    else
    {
         QMessageBox::information(this, "提示","操作失败,请检查输入的数据是否正确");
    }
    goodsMode->setQuery("select * from woker;");
    ReshowTable_people();
}

void MainWindow::on_pushButton_selectpeople_clicked()
{

   peopleMode->setQuery("select * from woker;");

   ReshowTable_people();

}


void MainWindow::on_pushButton_changepeople_clicked()
{
    QSqlQuery query;
    QString str = "update goods set name = '"+ ui->lineEdit_people_name->text() + "', sex='" + ui->lineEdit_people_sex->text()
            + "',age=" + ui->lineEdit_people_age->text() + ",phonenumber='" + ui->lineEdit_people_phonenumber->text()
            + "' where number='" + ui->lineEdit_goods_id->text() + "';";
    query.exec(str);
    QMessageBox::information(this, "修改成功", "表信息修改成功");
    goodsMode->setQuery("select * from woker;");
    ReshowTable_people();
}

void MainWindow::on_pushButton_deletepeople_clicked()
{
    QSqlQuery query;
    int currentrow = ui->tableView_people->currentIndex().row();
    peopleMode->removeRow(currentrow);
    if(currentrow != -1)//若选中一行
    {
        int ok  =  QMessageBox::warning(this,tr("删除当前行!"),tr("你确定删除当前行吗?"), QMessageBox::Yes,QMessageBox::No);
        //如确认删除
        if(ok == QMessageBox::Yes)
        {
            peopleMode->removeRow(currentrow);
            QString name = peopleMode->data(peopleMode->index(currentrow,0)).toString();//获取姓名
            QString del = "delete from woker where name='" + name + "';";
            query.exec(del);
            peopleMode->setQuery("select * from woker");
            ui->tableView_people->setModel(peopleMode);
            QMessageBox::information(this, "删除成功", "所选信息删除成功");
        }
    }
    else
        QMessageBox::information(this, "提示", "请选择你要删除的信息行");
}

连接本地mysql,如果要在别的地方运行,要有mysql的环境

相关推荐
童先生10 分钟前
Go 项目中实现类似 Java Shiro 的权限控制中间件?
开发语言·go
lulu_gh_yu11 分钟前
数据结构之排序补充
c语言·开发语言·数据结构·c++·学习·算法·排序算法
huanggang98211 分钟前
在Ubuntu22.04上使用Qt Creator开发ROS2项目
qt·ros2
Re.不晚35 分钟前
Java入门15——抽象类
java·开发语言·学习·算法·intellij-idea
老秦包你会37 分钟前
Qt第三课 ----------容器类控件
开发语言·qt
凤枭香40 分钟前
Python OpenCV 傅里叶变换
开发语言·图像处理·python·opencv
ULTRA??44 分钟前
C加加中的结构化绑定(解包,折叠展开)
开发语言·c++
远望清一色1 小时前
基于MATLAB的实现垃圾分类Matlab源码
开发语言·matlab
confiself1 小时前
大模型系列——LLAMA-O1 复刻代码解读
java·开发语言
XiaoLeisj1 小时前
【JavaEE初阶 — 多线程】Thread类的方法&线程生命周期
java·开发语言·java-ee