Qt 错误:QSqlQuery::value:尝试从表中检索统计信息时未定位在有效记录上 (QComboBox)



这是我用来从此表中获取 GoalsFor 统计数据的代码,用户使用以下代码从 ComboBox 中选择一支球队后:

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"),查询实际上并未返回该 。然后,这将返回无效-1。将其更改为"GoalsForH"以获取正确的列索引。

最新更新