Qt 错误:QSqlQuery::value:尝试从表中检索统计信息时未定位在有效记录上 (QComboBox)
Qt error: QSqlQuery::value: not positioned on a valid record when trying to retrive a stat from a table (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"
以获取正确的列索引。
相关文章:
- 欧拉项目#8答案是大以获得有效答案
- 调整大小后指向元素值的指针unordered_map有效?
- 为什么是0;C++中的有效语句
- 最高有效数字侧的第N位
- GCC对可能有效的代码抛出init list生存期警告
- 有效地使用std::unordered_map来插入或增加键的值
- c++中O(n^(1/3))中一个数的除数的有效计数
- 使用无符号字符数组有效存储内存
- 自定义先决条件对移动分配运算符有效吗
- 重新定位图像时如何前进到下一个内存块
- 为什么将值返回函数传递给重载=运算符对运算符函数有效,而对其他运算符无效
- 有哪些有效的方法可以消除一组 100 万个字符串>重复数据?
- 为什么这种直接初始化有效?(C++17)
- 递归函数有效,但无法记忆
- 在C++中初始化向量映射的最有效方法
- 如果变量名称不跟在 char* 后面,const char* 是否有效?
- 钳制迭代器是否有效
- 流填充字符的默认定位
- 如何有效地在 std::vector 中插入一对?
- C++模板 t 不是有效的模板类型