1

我想要做的是 query.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();
4

1 回答 1

2

您可以使用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。

于 2015-02-11T06:48:33.020 回答