Qt缓存数据库数据表示例:缓存对数据库的修改,手动提交保存更改:model->setEditStrategy(QSqlTableModel::OnManualSubmit)

这个示例展示了如何在Qt中使用QSqlTableModel缓存对数据库的修改。TableEditor类创建了一个对话框,用户可以修改数据,但更改不会立即保存。通过设置编辑策略为OnManualSubmit,用户需点击‘提交’按钮才会保存更改。在提交过程中,使用数据库事务确保数据一致性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

缓存表示例界面:

展示了如何使用表视图来访问数据库,缓存对数据的任何更改,直到用户使用按钮明确提交这些更改
在这里插入图片描述
该示例由一个类TableEditor组成,TableEditor是一个自定义对话框小部件,允许用户修改存储在数据库中的数据

TableEditor类定义

  • TableEditor类继承了QWidget,作为主窗口
class TableEditor : public QWidget
{
   
    Q_OBJECT

public:
    explicit TableEditor(const QString &tableName, QWidget *parent = nullptr);

private slots:
    void submit();

private:
    QPushButton *submitButton;
    QPushButton *revertButton;
    QPushButton *quitButton;
    QDialogButtonBox *buttonBox;
    QSqlTableModel *model;
};

TableEditor构造函数接受两个参数:第一个是对TableEditor对象将操作的数据库表的引用。另一个是指向父小部件的指针,并被传递给基类构造函数
QSqlTableModel类可用于向视图类(如QTableView)提供数据。QSqlTableModel类提供了一个可编辑的数据模型,使得从单个表中读写数据库记录成为可能。它建立在较低级别的SqlQuery类之上,该类提供了执行和操作SQL语句的方法。
另外还展示如何使用表视图来缓存对数据的任何更改,直到明确请求提交它们。为此,我们需要在模型和编辑器按钮之外声明一个submit()槽函数

  • main函数主要代码
int main(int argc, char *argv[])
{
   
    QApplication app(argc, argv);
    if (!createConnection())
        return 1;

    TableEditor editor("person");
    editor.show();
    return app.exec();
}
  • createConnection()函数定义在connection.h的头文件中,此函数创建内存临时数据库,建立三个数据表,并添加一些记录
static bool createConnection()
{
   
    QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(":memory:");
    if (!db.open()) {
   
        QMessageBox::critical(nullptr, QObject::tr("Cannot open database"),
            QObject::tr("Unable to establish a database connection.\n"
                        "This example needs SQLite support. Please read "
                        "the Qt SQL driver documentation for information how "
                        "to build it.\n\n"
                        "Click Cancel to exit."), QMessageBox::Cancel);
        return false;
    }

    QSqlQuery query;
    query.exec("create table person (id int primary key, "
               "firstname varchar(20), lastname varchar(20))");
    query.exec("insert into person values(101, 'Danny', 'Young')");
    query.exec("insert into person values(102, 'Christine', 'Holand')");
    query.exec("insert into person values(103, 'Lars', 'Gordon')");
    query.exec("insert into person values(104, 'Roberto', 'Robitaille')");
    query.exec("insert into person values(105, 'Maria', 'Papadopoulos')");

    query.exec("create table items (id int primary key,"
                                             "imagefile int,"
                                             "itemtype varchar(20),"
                                             "description varchar(100))");
    query.exec("insert into items "
               "values(0, 0, 'Qt',"
               "'Qt is a full development framework with tools designed to "
               "streamline the creation of stunning applications and  "
               "amazing user interfaces for desktop, embedded and mobile "
               "platforms.')");
    query.exec("insert into items "
               "values(1, 1, 'Qt Quick',"
               "'Qt Quick is a collection of techniques designed to help "
               "developers create intuitive, modern-looking, and fluid "
               "user interfaces using a CSS & JavaScript like language.')");
    query.exec("insert into items "
               "values(2, 2, 'Qt Creator',"
               "'Qt Creator is a powerful cross-platform integrated "
               "development environment (IDE), including UI design tools "
               "and on-device debuggi
void Widget::Select() //查询 { QString name = ui->lineEdit->text(); model->setFilter(QObject::tr("id = '%1'").arg(name)); //根据姓名进行筛选 model->select(); //显示结果 } void Widget::Delect() //删除当前行 { int curRow = ui->tableView->currentIndex().row(); //获取选中的行 model->removeRow(curRow); //删除该行 int ok = QMessageBox::warning(this,tr("删除当前行!"),tr("你确定" "删除当前行吗?"), QMessageBox::Yes,QMessageBox::No); if(ok == QMessageBox::No) { model->revertAll(); //如果不删除,则撤销 } else model->submitAll(); //否则提交,在数据库中删除该行 } void Widget::Add() //插入记录 { int rowNum = model->rowCount(); //获得表的行数 int id = 10; model->insertRow(rowNum); //添加一行 model->setData(model->index(rowNum,0),id); //model->submitAll(); //可以直接提交 } void Widget::Back() //返回全表 { model->setTable("student"); //重新关联表 model->setHeaderData(0, Qt::Horizontal, "Time"); model->setHeaderData(1, Qt::Horizontal, "Temperature"); model->select(); //这样才能再次显示整个表的内容 } void Widget::Amend() //提交修改 { model->database().transaction(); //开始事务操作 if (model->submitAll()) { model->database().commit(); //提交 } else { model->database().rollback(); //回滚 QMessageBox::warning(this, tr("tableModel"), tr("数据库错误: %1").arg(model->lastError().text())); } } void Widget::Get_time() { QString string; QTime current_time = QTime::currentTime(); int hour = current_time.hour(); int minute = current_time.minute(); int second = current_time.second(); // int msec = current_time.msec(); string=QString("%1").arg(hour)+":"+QString("%1").arg(minute) +":"+QString("%1").arg(second); ui->Receive->append(string); //qDebug() <rowCount(); //获得表的行数 // int id = 10; model->insertRow(rowNum); //添加一行 model->setData(model->index(rowNum,0),string); model->submitAll(); } void Widget::readMyCom() { QByteArray temp = myCom->readAll(); if(temp.size()!=0) { QString string; QTime current_time = QTime::currentTime(); int hour = current_time.hour(); int minute = current_time.minute(); int second = current_time.second(); // int msec = current_time.msec(); string=QString("%1").arg(hour)+":"+QString("%1").arg(minute) +":"+QString("%1").arg(second); ui->Receive->append(string); //qDebug() <rowCount(); //获得表的行数 // int id = 10; model->insertRow(rowNum); //添加一行 model->setData(model->index(rowNum,0),string); model->setData(model->index(rowNum,1),temp); model->submitAll(); data_light=temp.toInt(); } ui->Receive->append(temp); } void Widget::openCom() { QString portName = ui->portNameComboBox->currentText(); myCom = new Win_QextSerialPort(portName,QextSerialBase::EventDriven); myCom ->open(QIODevice::ReadWrite); if(ui->baudRateComboBox->currentText()==tr("9600")) myCom->setBaudRate(BAUD9600); else if(ui->baudRateComboBox->currentText()==tr("115200")) myCom->setBaudRate(BAUD115200); myCom->setFlowControl(FLOW_OFF); myCom->setTimeout(500); connect(myCom,SIGNAL(readyRead()),this,SLOT(readMyCom())); ui->openMyComBtn->setEnabled(false); ui->closeMyComBtn->setEnabled(true); ui->baudRateComboBox->setEnabled(false); ui->portNameComboBox->setEnabled(false); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值