Qt Creator中如何根据Sql Query结果做条件语句?

How to do conditional statements based on SqlQuery results in QtCreator?

我想做的是query.exec()一个DELETE语句,如果删除成功我想显示更新后的table,否则显示一个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 文档,此函数

Returns the number of rows affected by the result's SQL statement, or -1 if it cannot be determined. Note that for SELECT statements, the value is undefined; use size() instead. If the query is not active, -1 is returned.