当前位置: 代码迷 >> 综合 >> QT下的QSqlQueryModel类
  详细解决方案

QT下的QSqlQueryModel类

热度:45   发布时间:2023-09-29 17:29:16.0

QSqlTableModel,该类提供了一个可读写单张SQL表的可编辑数据模型。我们下面就对其的几个常用功能进行介绍,分别是修改,插入,删除,查询,和排序。

查询操作:

QSqlQueryModel *model = new QSqlQueryModel;QString temStr,strSQL="SELECT * FROM potion where ";temStr=this->ui->comboBox_6->currentText();strSQL+=temStr+"=";strSQL+="'"+this->ui->potion_cha->text()+"'";model->setQuery(strSQL);//这里直接设置SQL语句,忽略最后一个参数ui->tableView_5->setModel(model);//以下是视觉方面的效果,不加也没影响//隔行变色ui->tableView_5->setAlternatingRowColors(true);//设置行高int row_count = model->rowCount();for(int i =0; i < row_count; i++){ui->tableView_5->setRowHeight(i, 20);}

 

 

 

 

删除操作:
 QSqlQueryModel *model = new QSqlQueryModel;QString temStr,strSQL="delete FROM potion where ";temStr=this->ui->comboBox_7->currentText();strSQL+=temStr+"=";strSQL+="'"+this->ui->potion_del->text()+"'";model->setQuery(strSQL);//这里直接设置SQL语句,忽略最后一个参数

修改操作:

 

QSqlQueryModel *model = new QSqlQueryModel;QString temStr,strSQL="update potion set ";temStr=this->ui->comboBox_8->currentText();strSQL+=temStr+"=";strSQL+="'"+this->ui->potion_updata->text().trimmed()+"'";strSQL+=" where 药剂代号=";strSQL+=""+this->ui->potion_id->text().trimmed()+"";
//    query.exec(QObject::tr("update potion set id=333 where id=5"));model->setQuery(strSQL);//这里直接设置SQL语句,忽略最后一个参数

插入操作:

 QSqlQueryModel *model = new QSqlQueryModel;QString strSQL="INSERT INTO job (job_id, job_name, dept_id) VALUES (1, 2, 3) ";model->setQuery(strSQL);//这里直接设置SQL语句,忽略最后一个参数

将SQL数据显示在tableView

 ui->tableView_5->setModel(model);//以下是视觉方面的效果,不加也没影响//隔行变色ui->tableView_5->setAlternatingRowColors(true);//设置行高int row_count = model->rowCount();for(int i =0; i < row_count; i++){ui->tableView_5->setRowHeight(i, 20);}