如何在QtCreator中使用基于SqlQuery的条件语句?

时间:2015-02-11 06:42:34

标签: c++ sqlite qt-creator qsqlquery

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

1 个答案:

答案 0 :(得分: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   归还。