Qt error: QSqlQuery::value: not positioned on a valid record when trying to retrive a stat from a table (QComboBox)

Qt error: QSqlQuery::value: not positioned on a valid record when trying to retrive a stat from a table (QComboBox)

这是我用来从 this table after the user chooses a team from a ComboBox like this 获取 GoalsFor 统计数据的代码:

 void MainWindow::on_hometeam_currentIndexChanged(const QString &hometeam)
{
  QString hteam(hometeam);

  QSqlQuery q("SELECT GoalsForH FROM teams WHERE TEAM=hteam");
  q.exec();
  int fieldNo = q.record().indexOf("hometeam");
  q.next();

  qDebug() << q.value(fieldNo).toInt();

}

但这就是每当我选择团队时调试器总是显示的内容:

QSqlQuery::value: not positioned on a valid record
0

我尝试了我在网上遇到的一切,但似乎我正在做其他用户甚至文档所说的,但都无济于事,任何帮助将不胜感激,谢谢!

问题似乎出在 SQL 本身;因为 hteam 实际上并未在 SQL 中定义。相反,我建议使用 prepare 函数,该函数还可以处理过滤字符串以防止 SQL 注入。像下面这样的东西应该会给你你正在寻找的结果。

void MainWindow::on_hometeam_currentIndexChanged(const QString &hometeam)
{
  QString hteam(hometeam);

  QSqlQuery q;
  q.prepare("SELECT GoalsForH FROM teams WHERE TEAM=:hteam");
  q.bindValue(":hteam", hteam);
  if ( !q.exec() ) {
    qDebug() << q.lastError();
  } else {
    int fieldNo = q.record().indexOf("GoalsForH");
    while ( q.next() ) {
      qDebug() << q.value(fieldNo).toInt();
    }
  }
}

您还抓取了 indexOf("hometeam"),这实际上并未由查询返回。然后 returns -1 将无效。将其更改为 "GoalsForH" 以获得正确的列索引。