如何在QtCreator中基于SqlQuery结果执行条件语句



我想做的是查询.exec()一个DELETE语句,如果删除成功,我想显示更新的表,否则显示一个QMessageBox,说明名称不匹配。

我的印象是,如果DELETE语句找不到条目,那么query.exec()将为FALSE。但无论我为这个名字输入什么,它总是正确的。有解决这个问题的办法吗?谢谢大家。。。

所以我现在的代码是:

bool ok;
QInputDialog *dialog = new QInputDialog;
QString name = dialog->getText((QWidget*)this->parent(), tr("Enter Buyer to Delete:"),
                                          tr("Buyer Name:"), QLineEdit::Normal,
                                          "", &ok);
QSqlTableModel *model1;
QSqlQuery query;
query.prepare("DELETE from buyers WHERE name=:name");
query.addBindValue(name);
bool x = query.exec();      //<----PROBLEM: EVEN WITH INCORRECT name,
qDebug() << x;              // query.exec() RETURNS true ALTHOUGH delete
if (!x)                     // IS SUPPOSED TO FAIL 
{
    QMessageBox box;
    box.setInformativeText("No buyer found with name matching " + name);
    box.exec();
}
model1 = new QSqlTableModel;
model1->setTable("buyers");
model1->select();
model1->setHeaderData(0, Qt::Horizontal, tr("ID"));
model1->setHeaderData(1, Qt::Horizontal, tr("Name"));
model1->setHeaderData(2, Qt::Horizontal, tr("Location"));
model1->setHeaderData(3, Qt::Horizontal, tr("Phone"));
model1->setHeaderData(4, Qt::Horizontal, tr("Email"));
QTableView *view1 = new QTableView;
view1->setWindowTitle("Buyer List updated");
view1->setModel(model1);
view1->show();

您可以使用QSqlQuery::​numRowsAffected():

QSqlQuery query("your_query_here");
query.exec();
if(query.numRowsAffected() == 0)
{
    //didn't delete anything
}
else
{
    //worked fine
}

注意,根据Qt文档,此功能

返回受结果的SQL语句影响的行数,或-如果无法确定,则为1。请注意,对于SELECT语句,该值是未定义的;请改用size()。如果查询未激活,则-1返回。

相关内容

  • 没有找到相关文章

最新更新