十一、Qt数据库操作

news2024/11/16 5:43:41

一、Sql介绍

Qt Sql模块包含多个类,实现数据库的连接,Sql语句的执行,数据获取与界面显示,数据与界面直接使用Model/View结构。

1、使用Sql模块

(1)工程加入

QT += sql

(2)添加头文件

#include <QtSel>

2、Sql相关类

1、数据库相关类

  • QTableView:常用的数据库内容显示组件
  • QSalQuryModel:通过设置select语句查询获取数据库内容,数据只读。
  • QSqlTableModel:直接设置一个数据表的名称,可以获取苏韩剧表的全部记录,可以编辑。
  • QSqlRelationalTableModel:为单张的数据库表提供了一个编辑的数据模型,支持外键。

二、QSqltableModel

1、实现程序

在这里插入图片描述

(1)创建项目,基于QMainWindow

(2)添加类

在这里插入图片描述

(3)添加组件

在这里插入图片描述

(4)加载数据库

void MainWindow::openTable()
{
    tabModel = new QSqlTableModel(this, DB);
    tabModel->setTable("employee"); //设置数据表名称
    tabModel->setSort(tabModel->fieldIndex("empNo"), Qt::AscendingOrder); //按照员工号升序
    tabModel->setEditStrategy(QSqlTableModel::OnManualSubmit); //手动提交数据
    if(!tabModel->select())
    {
        QMessageBox::critical(this, "错误", "打开数据表错误,错误信息\n"
                              + tabModel->lastError().text());
        return;
    }

    // 修改表头
    tabModel->setHeaderData(tabModel->fieldIndex("empNo"), Qt::Horizontal, "工号");
    tabModel->setHeaderData(tabModel->fieldIndex("Name"), Qt::Horizontal, "姓名");
    tabModel->setHeaderData(tabModel->fieldIndex("Gender"), Qt::Horizontal, "性别");
    tabModel->setHeaderData(tabModel->fieldIndex("Height"), Qt::Horizontal, "身高");
    tabModel->setHeaderData(tabModel->fieldIndex("Birthday"), Qt::Horizontal, "出生日期");
    tabModel->setHeaderData(tabModel->fieldIndex("Mobile"), Qt::Horizontal, "手机号");
    tabModel->setHeaderData(tabModel->fieldIndex("Province"), Qt::Horizontal, "省份");
    tabModel->setHeaderData(tabModel->fieldIndex("City"), Qt::Horizontal, "城市");
    tabModel->setHeaderData(tabModel->fieldIndex("Depart"), Qt::Horizontal, "部门");
    tabModel->setHeaderData(tabModel->fieldIndex("Education"), Qt::Horizontal, "学历");
    tabModel->setHeaderData(tabModel->fieldIndex("Salary"), Qt::Horizontal, "薪资");
    tabModel->setHeaderData(tabModel->fieldIndex("Photo"), Qt::Horizontal, "照片");
    tabModel->setHeaderData(tabModel->fieldIndex("Memo"), Qt::Horizontal, "备注");

    theSelection = new QItemSelectionModel(tabModel);
    ui->tableView->setModel(tabModel);
    ui->tableView->setSelectionModel(theSelection);

    connect(theSelection, SIGNAL(currentChanged(QModelIndex, QModelIndex)),
            this, SLOT(on_currentChanged(QModelIndex, QModelIndex)));
    connect(theSelection, SIGNAL(currentRowChanged(QModelIndex, QModelIndex)),
            this, SLOT(on_currentRowChanged(QModelIndex, QModelIndex)));

    // 隐藏列
    ui->tableView->setColumnHidden(tabModel->fieldIndex("Photo"), true);
    ui->tableView->setColumnHidden(tabModel->fieldIndex("Memo"), true);

    dataMapper = new QDataWidgetMapper;
    dataMapper->setModel(tabModel);
    dataMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);

    dataMapper->addMapping(ui->spinBoxNum, tabModel->fieldIndex("empNo"));
    dataMapper->addMapping(ui->lineEditName, tabModel->fieldIndex("Name"));

    dataMapper->addMapping(ui->comboBoxSex, tabModel->fieldIndex("Gender"));
    dataMapper->addMapping(ui->doubleSpinBoxHeight, tabModel->fieldIndex("Height"));
    dataMapper->addMapping(ui->lineEditBirthday, tabModel->fieldIndex("Birthday"));
    dataMapper->addMapping(ui->lineEditPhone, tabModel->fieldIndex("Mobile"));
    dataMapper->addMapping(ui->comboBoxProvince, tabModel->fieldIndex("Province"));
    dataMapper->addMapping(ui->lineEditCity, tabModel->fieldIndex("City"));
    dataMapper->addMapping(ui->comboBoxWork, tabModel->fieldIndex("Depart"));
    dataMapper->addMapping(ui->comboBoxStudy, tabModel->fieldIndex("Education"));
    dataMapper->addMapping(ui->textEditInfo, tabModel->fieldIndex("Memo"));


    getFiledNames();
    ui->actOpen->setEnabled(false);
    ui->actAppend->setEnabled(true);
    ui->actDelete->setEnabled(true);
    ui->actInsert->setEnabled(true);
    ui->actScan->setEnabled(true);
    ui->groupBoxSort->setEnabled(true);
    ui->groupBoxFilter->setEnabled(true);

    // 使用delegate实现下拉选择
    QStringList strList;
    strList << "男" << "女";
    bool isEditable = false;
    delegateSex.setItem(strList, isEditable);
    ui->tableView->setItemDelegateForColumn(
        tabModel->fieldIndex("Gender"), &delegateSex);
}

void MainWindow::getFiledNames()
{
    QSqlRecord emptyRec = tabModel->record();
    for (int i = 0; i < emptyRec.count(); ++i)
    {
        ui->comboBoxFields->addItem(emptyRec.fieldName(i));
    }
}

void MainWindow::on_currentChanged(const QModelIndex &current, const QModelIndex &preivous)
{
    Q_UNUSED(current)
    Q_UNUSED(preivous)
    ui->actSubmit->setEnabled(tabModel->isDirty()); // 是否有数据修改
    ui->actRevert->setEnabled(tabModel->isDirty()); // 是否有数据修改
}

void MainWindow::on_currentRowChanged(const QModelIndex &current, const QModelIndex &preivous)
{
    ui->actDelete->setEnabled(current.isValid());
    ui->actAppend->setEnabled(current.isValid());
    ui->actInsert->setEnabled(current.isValid());

    if(! current.isValid())
    {
        ui->labelPhoto->clear();
        return;
    }
    dataMapper->setCurrentIndex(current.row());
    QSqlRecord curRec = tabModel->record(current.row());
    if(curRec.isNull("Photo"))
    {
        ui->labelPhoto->clear();
    }
    else
    {
        QByteArray data  = curRec.value("Photo").toByteArray();
        QPixmap pic;
        pic.loadFromData(data);
        ui->labelPhoto->setPixmap(pic.scaledToWidth(ui->labelPhoto->size().width()));
    }
}


void MainWindow::on_actOpen_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, "选择数据库文件",
                       "", "Sqlite数据库(*.db *.db3)");
    if(fileName.isEmpty())
    {
        return;
    }
    DB = QSqlDatabase::addDatabase("QSQLITE"); //添加数据库驱动
    DB.setDatabaseName(fileName); // 设置数据库名称
    if(!DB.open())
    {
        QMessageBox::warning(this, "错误", "打开数据库失败");
        return;
    }
    openTable();
}

在这里插入图片描述

(5)实现工具栏按钮功能

void MainWindow::on_actAppend_triggered()
{
    tabModel->insertRow(tabModel->rowCount(), QModelIndex());
    QModelIndex curIndex = tabModel->index(tabModel->rowCount() - 1, 1); // 插入后增加一行
    theSelection->clearSelection();
    theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);
    tabModel->setData(tabModel->index(curIndex.row(), 0), 2000 + tabModel->rowCount());
    tabModel->setData(tabModel->index(curIndex.row(), 2), "男");
    ui->actSubmit->setEnabled(true);
    ui->actRevert->setEnabled(true);
}

void MainWindow::on_actInsert_triggered()
{
    QModelIndex curIndex = theSelection->currentIndex();
    tabModel->insertRow(curIndex.row(), QModelIndex());
    theSelection->clearSelection();
    theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);

    tabModel->setData(tabModel->index(curIndex.row(), 0), 2000 + tabModel->rowCount());
    tabModel->setData(tabModel->index(curIndex.row(), 2), "男");
    ui->actSubmit->setEnabled(true);
    ui->actRevert->setEnabled(true);
}

void MainWindow::on_actDelete_triggered()
{
    QModelIndex curIndex = theSelection->currentIndex();
    tabModel->removeRow(curIndex.row());
    ui->actSubmit->setEnabled(true);
    ui->actRevert->setEnabled(true);
}

void MainWindow::on_actSubmit_triggered()
{
    bool result = tabModel->submitAll();
    if(!result)
    {
        QMessageBox::information(this, "信息", "数据提交错误,错误信息\n"
                                 + tabModel->lastError().text());
    }
    else
    {
        ui->actSubmit->setEnabled(false);
        ui->actRevert->setEnabled(false);
    }
}

void MainWindow::on_actRevert_triggered()
{
    tabModel->revertAll();
    ui->actSubmit->setEnabled(false);
    ui->actRevert->setEnabled(false);
}

void MainWindow::on_actSetPhoto_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, "选择图片", "", "照片(*.jpg *.png)");
    if(fileName.isEmpty())
    {
        return;
    }
    QByteArray data;
    QFile *file = new QFile(fileName);
    if(file->open(QIODevice::ReadOnly))
    {
        data = file->readAll();

        QModelIndex curIndex = theSelection->currentIndex();
        QSqlRecord curRec = tabModel->record(curIndex.row());
        curRec.setValue("Photo", data);
        tabModel->setRecord(curIndex.row(), curRec);

        QPixmap pic;
        pic.load(fileName);
        ui->labelPhoto->setPixmap(pic.scaledToWidth(ui->labelPhoto->width()));

        file->close();
    }
    delete file;
}

void MainWindow::on_actClearPhoto_triggered()
{
    QModelIndex curIndex = theSelection->currentIndex();
    QSqlRecord curRec = tabModel->record(curIndex.row());
    curRec.setNull("Photo");
    tabModel->setRecord(curIndex.row(), curRec);
    ui->labelPhoto->clear();
}

void MainWindow::on_actScan_triggered()
{
    if(tabModel->rowCount() != 0)
    {
        for (int i = 0; i < tabModel->rowCount(); ++i)
        {
            QSqlRecord aRec = tabModel->record(i);
            float salary = aRec.value("Salary").toFloat();
            salary *= 1.1;
            aRec.setValue("Salary", salary);
            tabModel->setRecord(i, aRec);
        }
        if(tabModel->submitAll())
        {
            QMessageBox::information(this, "信息", "涨工资完成");
        }
    }
}

void MainWindow::on_comboBoxFields_currentIndexChanged(int index)
{
    if(ui->rbtnAscend->isCheckable())
    {
        tabModel->setSort(index, Qt::AscendingOrder);
    }
    else
    {
        tabModel->setSort(index, Qt::DescendingOrder);
    }
    tabModel->select(); // 重新从数据库装载
}

void MainWindow::on_rbtnAscend_clicked()
{
    tabModel->setSort(ui->comboBoxFields->currentIndex(), Qt::AscendingOrder);
    tabModel->select(); // 重新从数据库装载
}

void MainWindow::on_rbtnDescend_clicked()
{
    tabModel->setSort(ui->comboBoxFields->currentIndex(), Qt::DescendingOrder);
    tabModel->select(); // 重新从数据库装载
}

void MainWindow::on_rbtnMan_clicked()
{
    tabModel->setFilter("Gender='男'");
}

void MainWindow::on_rbtnWoman_clicked()
{
    tabModel->setFilter("Gender='女'");
}

void MainWindow::on_rbtnAll_clicked()
{
    tabModel->setFilter("");
}

三、QSqlQueryModel

1、相关类

QAbstractTableModel
	QSqlQueryModel //封装了指向SELECT语句从数据库查询数据的功能
		QSqlTableModel
			QSqlRelationalTableModel

2、实现程序

在这里插入图片描述

1、创建项目,基于QMainWindow

2、添加图标资源文件,添加工具按钮

3、添加组件

在这里插入图片描述

4、实现功能

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    qryModel = new QSqlQueryModel(this);
    theSelection = new QItemSelectionModel(qryModel);
    dataMapper = new QDataWidgetMapper(this);
    dataMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
    dataMapper->setModel(qryModel);

    ui->tableView->setModel(qryModel);
    ui->tableView->setSelectionModel(theSelection);

    connect(theSelection, SIGNAL(currentRowChanged(QModelIndex, QModelIndex)),
            this, SLOT(on_currentRowChanged(QModelIndex, QModelIndex)));
}

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

#include <QFileDialog>
#include <QMessageBox>
void MainWindow::on_actOpenDB_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, "打开数据库", "",
                       "数据库文件(*.db *.db3)");
    if(fileName.isEmpty())
    {
        return;
    }
    DB = QSqlDatabase::addDatabase("QSQLITE");
    DB.setDatabaseName(fileName);
    if(!DB.open())
    {
        QMessageBox::warning(this, "错误", "打开数据库失败");
        return;
    }

    qryModel->setQuery("SELECT EmpNo,Name,Gender,Height,Birthday,Mobile,Province,City,Depart,Education,Salary FROM employee ORDER BY EMpNo", DB);
    if(qryModel->lastError().isValid())
    {
        QMessageBox::critical(this, "错误", "查询失败\n" + qryModel->lastError().text());
        return;
    }

    qryModel->setHeaderData(0, Qt::Horizontal, "工号");
    qryModel->setHeaderData(2, Qt::Horizontal, "性别");

    dataMapper->addMapping(ui->spinBoxNum, 0);
    dataMapper->addMapping(ui->lineEditName, 1);
    dataMapper->addMapping(ui->comboBoxSex, 2);
    dataMapper->addMapping(ui->doubleSpinBoxHeight, 3);
    dataMapper->addMapping(ui->lineEditBirthday, 4);
    dataMapper->addMapping(ui->lineEditPhone, 5);
    dataMapper->addMapping(ui->comboBoxProvince, 6);
    dataMapper->addMapping(ui->lineEditCity, 7);
    dataMapper->addMapping(ui->comboBoxWork, 8);
    dataMapper->addMapping(ui->comboBoxStudy, 9);
    dataMapper->addMapping(ui->textEditInfo, 10);
    // dataMapper->toFirst();

    ui->actOpenDB->setEnabled(false);

}

void MainWindow::on_currentRowChanged(const QModelIndex &current, const QModelIndex &previous)
{
    if(!current.isValid())
    {
        ui->labelPhoto->clear();
        return;
    }

    dataMapper->setCurrentModelIndex(current);
    bool first = (current.row() == 0);
    bool last = (current.row() == qryModel->rowCount() - 1);

    ui->actRecFirst->setEnabled(!first);
    ui->actRecPrevious->setEnabled(!first);
    ui->actRecNext->setEnabled(!last);
    ui->actRecLast->setEnabled(!last);

    int curRecNo = theSelection->currentIndex().row();
    QSqlRecord curRec = qryModel->record(curRecNo);
    int empNo = curRec.value("EmpNo").toInt();
    QSqlQuery query;
    query.prepare("select EmpNo,Memo,Photo from employee where EmpNo = :ID");
    query.bindValue(":ID", empNo); //防注入
    query.exec();
    query.first(); // 回到第一条记录

    if(qryModel->lastError().isValid())
    {
        QMessageBox::critical(this, "错误", "查询失败\n" + qryModel->lastError().text());
        return;
    }

    QVariant va = query.value("Photo");
    if(!va.isValid())
    {
        ui->labelPhoto->clear();
    }
    else
    {
        QPixmap pic;
        QByteArray data = va.toByteArray();
        pic.loadFromData(data);

        ui->labelPhoto->setPixmap(pic.scaledToWidth(ui->labelPhoto->size().width()));
    }

    QVariant va2 = query.value("Memo");
    ui->textEditInfo->setPlainText(va2.toString());
}

void MainWindow::on_actRecFirst_triggered()
{
    dataMapper->toFirst();

    int index = dataMapper->currentIndex();
    QModelIndex curIndex = qryModel->index(index, 1);

    theSelection->clearSelection();
    theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);
}

void MainWindow::on_actRecPrevious_triggered()
{
    dataMapper->toPrevious();

    int index = dataMapper->currentIndex();
    QModelIndex curIndex = qryModel->index(index, 1);

    theSelection->clearSelection();
    theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);
}

void MainWindow::on_actRecNext_triggered()
{
    dataMapper->toNext();

    int index = dataMapper->currentIndex();
    QModelIndex curIndex = qryModel->index(index, 1);

    theSelection->clearSelection();
    theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);
}

void MainWindow::on_actRecLast_triggered()
{
    dataMapper->toLast();

    int index = dataMapper->currentIndex();
    QModelIndex curIndex = qryModel->index(index, 1);

    theSelection->clearSelection();
    theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select);
}

四、QSqlQuery

QSqlQuery是可以执行任意SQL语句的类,如SELECT、INSERT、UPDATE、DELETE等。

1、实现程序

在这里插入图片描述

(1)创建项目,基于QMainWindow

(2)添加工具栏按钮

(3)添加对话框

在这里插入图片描述
在这里插入图片描述

#include "dialogdata.h"
#include "ui_dialogdata.h"

DialogData::DialogData(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogData)
{
    ui->setupUi(this);
}

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

void DialogData::setUpdateRecord(QSqlRecord &recData)
{
    mRecord = recData;
    ui->spinBoxEmpNo->setEnabled(false);
    setWindowTitle("更新记录");

    // 更新界面
    ui->spinBoxEmpNo->setValue(recData.value("EmpNo").toInt());
    ui->lineEditName->setText(recData.value("Name").toString());
    ui->comboBoxSex->setCurrentText(recData.value("Gender").toString());
    ui->doubleSpinBoxHeight->setValue(recData.value("Height").toFloat());
    ui->lineEditBirthday->setText(recData.value("Birthday").toString());
    ui->lineEditPhone->setText(recData.value("Mobile").toString());
    ui->comboBoxProvince->setCurrentText(recData.value("Province").toString());
    ui->lineEditCity->setText(recData.value("City").toString());
    ui->comboBoxDepart->setCurrentText(recData.value("Depart").toString());
    ui->comboBoxEducation->setCurrentText(recData.value("Education").toString());
    ui->spinBoxSalary->setValue(recData.value("Salary").toInt());
    ui->textEditInfo->setText(recData.value("Memo").toString());

    QVariant va = recData.value("Photo");
    if(!va.isValid())
    {
        ui->labelPhoto->clear();
    }
    else
    {
        QByteArray data = va.toByteArray();
        QPixmap pic;
        pic.loadFromData(data);
        ui->labelPhoto->setPixmap(pic.scaledToWidth(ui->labelPhoto->size().width()));
    }
}

void DialogData::setInsertRecord(QSqlRecord &recData)
{
    mRecord = recData;
    ui->spinBoxEmpNo->setEnabled(true);
    setWindowTitle("新建记录");

    ui->spinBoxEmpNo->setValue(recData.value("EmpNo").toInt());
}

QSqlRecord DialogData::getRecordData()
{
    mRecord.setValue("EmpNo", ui->spinBoxEmpNo->value());
    mRecord.setValue("Name", ui->lineEditName->text());
    mRecord.setValue("Gender", ui->comboBoxSex->currentText());
    mRecord.setValue("Height", ui->doubleSpinBoxHeight->value());
    mRecord.setValue("Birthday", ui->lineEditBirthday->text());
    mRecord.setValue("Mobile", ui->lineEditPhone->text());
    mRecord.setValue("Province", ui->comboBoxProvince->currentText());
    mRecord.setValue("City", ui->lineEditCity->text());
    mRecord.setValue("Depart", ui->comboBoxDepart->currentText());
    mRecord.setValue("Education", ui->comboBoxEducation->currentText());
    mRecord.setValue("Salary", ui->spinBoxSalary->value());
    mRecord.setValue("Memo", ui->textEditInfo->toPlainText());

    return mRecord;
}

#include <QFileDialog>
void DialogData::on_btnLoadPhoto_clicked()
{
    QString fileName = QFileDialog::getOpenFileName(this, "选择图片", "",
                       "图片(*.png *.jpg)");
    if(fileName.isEmpty())
    {
        return;
    }

    QByteArray data;
    QFile *file = new QFile(fileName);
    file->open(QIODevice::ReadOnly);
    data = file->readAll();
    file->close();
    delete file;

    mRecord.setValue("Photo", data);
    QPixmap pic;
    pic.loadFromData(data);
    ui->labelPhoto->setPixmap(pic.scaledToWidth(ui->labelPhoto->size().width()));
}

void DialogData::on_btnClearPhoto_clicked()
{

}

(4)工具栏按钮功能

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QMessageBox>

#include "dialogdata.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setCentralWidget(ui->tableView);

    qryModel = new QSqlQueryModel;
    theSelection = new QItemSelectionModel(qryModel);

    ui->tableView->setModel(qryModel);
    ui->tableView->setSelectionModel(theSelection);

    connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)),
            this, SLOT(on_TableView_doubleClicked(QModelIndex)));
}

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

void MainWindow::openTable()
{
    qryModel->setQuery("SELECT EmpNo,Name,Gender,Height,Birthday,Mobile,Province,City,Depart,Education,Salary From employee order by EmpNo");
    if(qryModel->lastError().isValid())
    {
        QMessageBox::warning(this, "错误", "SqlCmdError" + qryModel->lastError().text());
        return;
    }

    qryModel->setHeaderData(0, Qt::Horizontal, "工号");
    qryModel->setHeaderData(1, Qt::Horizontal, "姓名");
    qryModel->setHeaderData(2, Qt::Horizontal, "性别");
    qryModel->setHeaderData(3, Qt::Horizontal, "身高");
    qryModel->setHeaderData(4, Qt::Horizontal, "出生日期");
    qryModel->setHeaderData(5, Qt::Horizontal, "手机");
    qryModel->setHeaderData(6, Qt::Horizontal, "省份");
    qryModel->setHeaderData(7, Qt::Horizontal, "城市");
    qryModel->setHeaderData(8, Qt::Horizontal, "部门");
    qryModel->setHeaderData(9, Qt::Horizontal, "学历");
    qryModel->setHeaderData(10, Qt::Horizontal, "工资");

    //    ui->tableView->resizeColumnsToContents(); // 自动调整列宽
    //    ui->tableView->horizontalHeader()->setStretchLastSection(true); //拉伸最后一列

    ui->actOpenDB->setEnabled(false);
    ui->actRecInsert->setEnabled(true);
    ui->actRecDelete->setEnabled(true);
    ui->actRecEdit->setEnabled(true);
    ui->actScan->setEnabled(true);


}

#include <QFileDialog>

void MainWindow::on_actOpenDB_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, "选择数据库",
                       "", "SQlite数据库(*.db *.db3)");
    if(fileName.isEmpty())
    {
        return;
    }

    DB = QSqlDatabase::addDatabase("QSQLITE");
    DB.setDatabaseName(fileName);
    if(!DB.open())
    {
        QMessageBox::warning(this, "错误", "打开数据库失败");
        return;
    }

    openTable();

}

void MainWindow::on_actRecInsert_triggered()
{
    QSqlQuery query;
    query.exec("select * from employee where EmpNo = -1");

    DialogData *dataDlg = new DialogData;
    Qt::WindowFlags flags = dataDlg->windowFlags();
    dataDlg->setWindowFlags(flags | Qt::MSWindowsFixedSizeDialogHint); //固定大小

    QSqlRecord curData = query.record();
    curData.setValue("EmpNo", qryModel->rowCount() + 1000);
    dataDlg->setInsertRecord(curData);

    int ret = dataDlg->exec();
    if(ret == QDialog::Accepted)
    {
        QSqlRecord recData =  dataDlg->getRecordData();
        query.prepare("INSERT INTO employee (EmpNo,Name,Gender,Height,Birthday,Mobile,Province,City,Depart,Education,Salary,Memo,Photo) "
                      "VALUES(:EmpNo,:Name,:Gender,:Height,:Birthday,:Mobile,:Province,:City,:Depart,:Education,:Salary,:Memo,:Photo)");
        query.bindValue(":EmpNo", recData.value("EmpNo"));
        query.bindValue(":Name", recData.value("Name"));
        query.bindValue(":Gender", recData.value("Gender"));
        query.bindValue(":Height", recData.value("Height"));
        query.bindValue(":Birthday", recData.value("Birthday"));
        query.bindValue(":Mobile", recData.value("Mobile"));
        query.bindValue(":Province", recData.value("Province"));
        query.bindValue(":City", recData.value("City"));
        query.bindValue(":Depart", recData.value("Depart"));
        query.bindValue(":Education", recData.value("Education"));
        query.bindValue(":Salary", recData.value("Salary"));
        query.bindValue(":Memo", recData.value("Memo"));
        query.bindValue(":Photo", recData.value("Photo"));

        if(!query.exec())
        {
            QMessageBox::critical(this, "error", "Information:" + query.lastError().text());
        }
        else
        {
            qryModel->setQuery("SELECT EmpNo,Name,Gender,Height,Birthday,Mobile,Province,City,Depart,Education,Salary From employee order by EmpNo");
            if(qryModel->lastError().isValid())
            {
                QMessageBox::warning(this, "错误", "SqlCmdError" + qryModel->lastError().text());
                return;
            }
        }
    }
    delete dataDlg;
}

void MainWindow::on_actRecEdit_triggered()
{
    int curRecNo = theSelection->currentIndex().row();
    QSqlRecord curRec = qryModel->record(curRecNo);
    int empNo = curRec.value("EmpNo").toInt();
    QSqlQuery query;
    query.prepare("select * from employee where EmpNo = :ID");
    query.bindValue(":ID", empNo);
    query.exec();
    query.first();
    if(!query.isValid())
    {
        return;
    }

    curRec = query.record();
    DialogData *dataDlg = new DialogData;
    Qt::WindowFlags flags = dataDlg->windowFlags();
    dataDlg->setWindowFlags(flags | Qt::MSWindowsFixedSizeDialogHint); //固定大小
    dataDlg->setUpdateRecord(curRec);

    int ret = dataDlg->exec();
    if(ret == QDialog::Accepted)
    {
        QSqlRecord recData =  dataDlg->getRecordData();
        query.prepare("update employee set "
                      "Name=:Name,Gender=:Gender,Height=:Height,Birthday=:Birthday,"
                      "Mobile=:Mobile,Province=:Province,City=:City,Depart=:Depart,"
                      "Education=:Education,Salary=:Salary,Memo=:Memo,Photo=:Photo where EmpNo=:ID"
                     );
        query.bindValue(":Name", recData.value("Name"));
        query.bindValue(":Gender", recData.value("Gender"));
        query.bindValue(":Height", recData.value("Height"));
        query.bindValue(":Birthday", recData.value("Birthday"));
        query.bindValue(":Mobile", recData.value("Mobile"));
        query.bindValue(":Province", recData.value("Province"));
        query.bindValue(":City", recData.value("City"));
        query.bindValue(":Depart", recData.value("Depart"));
        query.bindValue(":Education", recData.value("Education"));
        query.bindValue(":Salary", recData.value("Salary"));
        query.bindValue(":Memo", recData.value("Memo"));
        query.bindValue(":Photo", recData.value("Photo"));
        query.bindValue(":ID", recData.value("EmpNo"));

        if(!query.exec())
        {
            QMessageBox::critical(this, "error", "Information:" + query.lastError().text());
        }
        else
        {
            qryModel->setQuery("SELECT EmpNo,Name,Gender,Height,Birthday,Mobile,Province,City,Depart,Education,Salary From employee order by EmpNo");
            if(qryModel->lastError().isValid())
            {
                QMessageBox::warning(this, "错误", "SqlCmdError" + qryModel->lastError().text());
                return;
            }
        }
    }
    delete dataDlg;
}

void MainWindow::on_actRecDelete_triggered()
{
    int curRecNo = theSelection->currentIndex().row();
    QSqlRecord curRec = qryModel->record(curRecNo);
    int empNo = curRec.value("EmpNo").toInt();

    QSqlQuery queryDelete;
    queryDelete.prepare("delete from employee where EmpNo=:ID");
    queryDelete.bindValue(":ID", empNo);
    if(!queryDelete.exec())
    {
        QMessageBox::warning(this, "错误", "SqlCmdError" + queryDelete.lastError().text());
    }
    else
    {
        qryModel->setQuery("SELECT EmpNo,Name,Gender,Height,Birthday,Mobile,Province,City,Depart,Education,Salary From employee order by EmpNo");
        if(qryModel->lastError().isValid())
        {
            QMessageBox::warning(this, "错误", "SqlCmdError" + qryModel->lastError().text());
            return;
        }
    }

}

void MainWindow::on_actScan_triggered()
{
    QSqlQuery queryEmList;
    queryEmList.exec("select EmpNo,Salary From employee order by EmpNo");
    queryEmList.first();

    QSqlQuery queryUpdate;
    queryUpdate.prepare("update employee set Salary=:Salary where EmpNo=:ID");
    while (queryEmList.isValid())
    {
        int empID = queryEmList.value("EmpNo").toInt();
        float salary = queryEmList.value("Salary").toFloat() + 1000;

        queryUpdate.bindValue(":Salary", salary);
        queryUpdate.bindValue(":ID", empID);
        queryUpdate.exec();
        if(queryUpdate.lastError().isValid())
        {
            break;
        }

        queryEmList.next();
    }

    qryModel->setQuery("SELECT EmpNo,Name,Gender,Height,Birthday,Mobile,Province,City,Depart,Education,Salary From employee order by EmpNo");
    if(qryModel->lastError().isValid())
    {
        QMessageBox::warning(this, "错误", "SqlCmdError" + qryModel->lastError().text());
        return;
    }
}

void MainWindow::on_TableView_doubleClicked(QModelIndex index)
{
    Q_UNUSED(index)
    on_actRecEdit_triggered();
}

在这里插入图片描述

五、QSelRelationalTableModel

QSelRelationalTableModel类为单张的数据库提供了一个可以编辑的数据模型,它支持外键。
QAbstractTableModel
	QSqlQueryModel //封装了指向SELECT语句从数据库查询数据的功能
		QSqlTableModel
			QSqlRelationalTableModel

1、实现程序

在这里插入图片描述

(1)创建项目,基于QMainWindow

在这里插入图片描述

(2)添加图标资源

(3)实现工具栏功能

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setCentralWidget(ui->tableView);




}

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


#include <QFileDialog>
#include <QMessageBox>
void MainWindow::on_actOpenDB_triggered()
{
    QString fileName = QFileDialog::getOpenFileName(this, "打开数据库", "",
                       "Sqlite数据库(*.db *.db3)");
    if(fileName.isEmpty())
    {
        return;
    }

    DB = QSqlDatabase::addDatabase("QSQLITE");
    DB.setDatabaseName(fileName);
    if(!DB.open())
    {
        QMessageBox::warning(this, "错误", "打开数据库失败");
    }

    tabModel = new QSqlRelationalTableModel(this, DB);
    tabModel->setTable("studInfo");
    tabModel->setEditStrategy(QSqlTableModel::OnManualSubmit);
    tabModel->setSort(0, Qt::AscendingOrder);

    tabModel->setHeaderData(0, Qt::Horizontal, "学号");
    tabModel->setHeaderData(1, Qt::Horizontal, "姓名");
    tabModel->setHeaderData(2, Qt::Horizontal, "性别");
    tabModel->setHeaderData(3, Qt::Horizontal, "学院");
    tabModel->setHeaderData(4, Qt::Horizontal, "专业");

    tabModel->setRelation(3, QSqlRelation("departments", "departID", "department"));
    tabModel->setRelation(4, QSqlRelation("majors", "majorID", "major"));


    theSelection = new QItemSelectionModel(tabModel);
    ui->tableView->setModel(tabModel);
    ui->tableView->setSelectionModel(theSelection);

    // 表格添加代理(学院与专业下拉选)
    ui->tableView->setItemDelegate(new QSqlRelationalDelegate(ui->tableView));
    tabModel->select();

    ui->actOpenDB->setEnabled(false);
    ui->actRecAppend->setEnabled(true);
    ui->actRecInsert->setEnabled(true);
    ui->actRecDelete->setEnabled(true);
    ui->actFields->setEnabled(true);

}

void MainWindow::on_actFields_triggered()
{
    QSqlRecord emptyRec = tabModel->record();
    QString str;
    for (int var = 0; var < emptyRec.count(); ++var)
    {
        str = str + emptyRec.fieldName(var) + "\n";
    }
    QMessageBox::information(this, "字段名称", str);
}

void MainWindow::on_actRecAppend_triggered()
{
    tabModel->insertRow(tabModel->rowCount(), QModelIndex()); // 在末尾添加一条
    QModelIndex curIndex = tabModel->index(tabModel->rowCount() - 1, 1); //
    theSelection->clearSelection(); // 清空选择项
    theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select); // 设置新的选项

    ui->actRevert->setEnabled(true);
    ui->actSubmit->setEnabled(true);
}

void MainWindow::on_actRecInsert_triggered()
{
    QModelIndex curIndex = ui->tableView->currentIndex();
    tabModel->insertRow(curIndex.row(), QModelIndex()); // 添加一条
    theSelection->clearSelection(); // 清空选择项
    theSelection->setCurrentIndex(curIndex, QItemSelectionModel::Select); // 设置新的选项

    ui->actRevert->setEnabled(true);
    ui->actSubmit->setEnabled(true);
}

void MainWindow::on_actRevert_triggered()
{
    tabModel->revertAll();
    ui->actSubmit->setEnabled(false);
    ui->actRevert->setEnabled(false);
}

void MainWindow::on_actSubmit_triggered()
{
    bool res = tabModel->submitAll();
    if(!res)
    {
        QMessageBox::information(this, "信息", "数据保存错误\n" + tabModel->lastError().text(),
                                 QMessageBox::Ok, QMessageBox::NoButton);
    }
    else
    {
        ui->actSubmit->setEnabled(false);
        ui->actRevert->setEnabled(false);
    }
}

void MainWindow::on_actRecDelete_triggered()
{
    QModelIndex curIndex = ui->tableView->currentIndex();
    QModelIndex nextIndex = tabModel->index(curIndex.row() + 1, 0);

    tabModel->removeRow(curIndex.row()); // 删除
    theSelection->clearSelection(); // 清空选择项
    theSelection->setCurrentIndex(nextIndex, QItemSelectionModel::Select); // 设置新的选项

    ui->actRevert->setEnabled(true);
    ui->actSubmit->setEnabled(true);
}

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1468830.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【SRE系列】--部署gitlab

1、部署gitlab 1.1下载gitlab安装包并安装 下载地址&#xff1a;https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/ubuntu/pool/ rootk8s-gitlab:~# wget https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/ubuntu/pool/bionic/main/g/gitlab-ce/gitlab-ce_16.1.4-ce.0_amd64.d…

抖音视频提取软件使用功能|抖音视频下载工具

我们的抖音视频提取软件是一款功能强大、易于操作的工具&#xff0c;旨在解决用户在获取抖音视频时需要逐个复制链接、下载的繁琐问题。我们的软件支持通过关键词搜索和分享链接两种方式获取抖音视频&#xff0c;方便用户快速找到自己感兴趣的内容。 主要功能模块&#xff1a;…

Linux之JAVA环境配置jdkTomcatMySQL

目录 一. 安装jdk 1.1 查询是否有jdk 1.2 解压 1.3 配置环境变量 二. 安装Tomcat&#xff08;开机自启动&#xff09; 2.1 解压 2.2 启动tomcat 2.3 防火墙设置 2.4 创建启动脚本&#xff08;设置自启动&#xff0c;服务器开启即启动&#xff09; 三. MySQL安装&#xff08;…

【前端素材】推荐优质后台管理系统Sneat平台模板(附源码)

一、需求分析 后台管理系统是一种用于管理网站、应用程序或系统的工具&#xff0c;它通常作为一个独立的后台界面存在&#xff0c;供管理员或特定用户使用。下面详细分析后台管理系统的定义和功能&#xff1a; 1. 定义 后台管理系统是一个用于管理和控制网站、应用程序或系统…

Guitar Pro8.2吉他软件2024中文版功能特点介绍

Guitar Pro 8.2是一款功能强大的吉他乐谱软件&#xff0c;专为吉他手、音乐制作人和音乐爱好者设计。它提供了丰富的功能&#xff0c;帮助用户轻松创建、编辑、打印和分享吉他乐谱。以下是Guitar Pro 8.2的主要功能特点&#xff1a; Guitar Pro 2024 win-安装包下载如下&#x…

go interface{} 和string的转换问题

1.遇到的问题 问题来源于,我sql模版拼接遇到的问题。 首先&#xff0c;这样是没有问题的。 var qhx interface{} "qhx"s : qhx.(string)fmt.Println(s) 但是当我在这段代码里用:1.类型断言 var sqlStr "select * from tx_user where username %s" join…

leetcode——hot1

两数之和 class Solution {public int[] twoSum(int[] nums, int target) {int[] arrs new int[2];for(int i 0; i < nums.length - 1; i){for(int j i 1; j < nums.length; j){if(nums[i] nums[j] target){arrs[0] i;arrs[1] j;break;}}}return arrs;} }

sql注入 [极客大挑战 2019]FinalSQL1

打开题目 点击1到5号的结果 1号 2号 3号 4号 5号 这里直接令传入的id6 传入id1^1^1 逻辑符号|会被检测到&#xff0c;而&感觉成了注释符&#xff0c;&之后的内容都被替换掉了。 传入id1|1 直接盲注比较慢&#xff0c;还需要利用二分法来编写脚本 这里利用到大佬的脚…

C++——基础语法(3):内联函数、auto关键字、基于范围的for循环、空指针nullptr

6. 内联函数 在函数前加入inline修饰即可将函数变为内联函数。所谓内联函数&#xff0c;就是在编译时C编译器会将函数体在调用内联函数的地方展开&#xff0c;从而省去了调用函数的栈帧开销&#xff0c;提高程序运行效率。 inline int Add(int a, int b) {return a b; } int …

【电子书】设计制作

资料 wx&#xff1a;1945423050 整理了一些互联网电子书&#xff0c;推荐给大家 设计制作 3D打印建模&#xff1a;Autodesk 123D Design详解与实战 第2版.epub3ds Max 2016中文版标准教程.epubAfter Effects CS 6影视特效与栏目包装实战全攻略(第2版&#xff09;.epubAfter E…

欧瑞康真空TTR91莱宝ITR90真空计KA09420GA09使用说明接线图

欧瑞康真空TTR91莱宝ITR90真空计KA09420GA09使用说明接线图

RocketMQ快速实战以及集群架构原理详解

RocketMQ快速实战以及集群架构原理详解 组成部分 启动Rocket服务之前要先启动NameServer NameServer 提供轻量级Broker路由服务&#xff0c;主要是提供服务注册 Broker 实际处理消息存储、转发等服务的核心组件 Producer 消息生产者集群&#xff0c;通常为业务系统中的一个功…

操作系统访问控制机制

使用访问控制技术&#xff0c;可以设置用户对系统资源的访问权限&#xff0c;即限定用户只能访问允许访问的资源。访问控制还可以通过设置文件的属性&#xff0c;来保护文件只能被读而不能被修改&#xff0c;或只允许核准的用户对其进行修改等。 1.1 保护域 把一个进程能对某…

11-pytorch-使用自己的数据集测试

b站小土堆pytorch教程学习笔记 import torch import torchvision from PIL import Image from torch import nnimg_path ../imgs/dog.png imageImage.open(img_path) print(image) # imageimage.convert(RGB)transformtorchvision.transforms.Compose([torchvision.transforms.…

stm32利用CubeMX完成按键控制LED灯的点亮与熄灭

首先画电图&#xff0c;如下&#xff1a;&#xff08;会话最小系统后就可以不画了&#xff0c;如果要是画实物的话必须要有的&#xff0c;不能忘&#xff0c;模拟就无所谓了&#xff09; 然后是CubeMX设置时钟 这次使用的是内部8M时钟&#xff0c;这样能避免proteus闪退的情况&…

虚 拟 化原理

1 概念&#xff1a; ①通俗理解&#xff1a; 虚拟化是在硬件和操作系统之间的实践 ②通过对计算机的服务层级的理解&#xff0c;理解虚拟化概念 抽离层级之间的依赖关系&#xff08;服务器虚拟化&#xff09; 2 虚拟化分类 ①按架构分类 ◆寄居架构&#xff1a;装在操作系统上…

鸿蒙LiteOS-M 内核初始化

目录 一、LiteOS-M 初始化内核二、LOS_KernelInit代码分析三、LOS_Start代码解析坚持就有收获 一、LiteOS-M 初始化内核 在LiteOS-M应用程序中&#xff0c;系统初始化如下&#xff1a; /*** brief This is the ohos entry, and you could call this in your main funciton af…

Flutter(一):安装和环境配置、创建Flutter项目

安装和环境配置、创建Flutter项目 Flutter 下载方式1方式2 Flutter 环境配置配置国内镜像站点解压 Flutter将 flutter 添加到系统环境变量中运行 flutter doctor来验证安装 Android Studio下载插件创建项目安装 Android SDK 工具在模拟器上运行 Flutter 下载 方式1 全版本&…

C++基础知识(四:类的学习)

类 类指的就是对同一类对象&#xff0c;把所有的属性都封装起来&#xff0c;你也可以把类看成一个高级版的结构体。 【1】定义 class 类名 { 访问权限:成员属性; 访问权限:成员方法; }访问权限&#xff1a; public:共有的&#xff0c;类内、类外和子类中都可以访问 private:私有…

Matlab: Introduction to Hybrid Beamforming

文章目录 来源混合波束赋形的基本概念System Setup 来源 在matlab的命令行输入 doc hybrid beamforming 混合波束赋形的基本概念 混合波束形成简介 本例介绍了混合波束形成的基本概念&#xff0c;并说明了如何模拟这种系统。 现代无线通信系统使用空间复用来提高散射体丰富…