我一直收到一条错误消息,说我的价值不在有效记录上。我已经在MySQL中成功执行了我的查询,但我认为我在代码中忽略了一些东西。
query = QtSql.QSqlQuery("select patient_id," +
"(SUM(IF(uom_id = 1, value, 0)) / SUM(IF(uom_id = 1, 1, 0))) AS `Average radius`," +
"(SUM(IF(uom_id = 2, value, 0)) / SUM(IF(uom_id = 2, 1, 0))) AS `Average Volume`," +
"(SUM(IF(uom_id = 3, value, 0)) / SUM(IF(uom_id = 3, 1, 0))) AS `Average SA`" +
"from measurements" +
"WHERE image_id = " + self.dbImage.id.toString() +
"AND status = 'A'" +
"GROUP BY patient_id", self.db)
query.next()
radius_acc = query.value(1).toDouble()
volume_acc = query.value(2).toDouble()
SA_acc = query.value(3).toDouble()
print('average of previously accepted measurements includes ' +
'radius = ' + str(radius_acc) +
'volume = ' + str(volume_acc) +
'SA = ' + str(SA_acc))
具体来说,我想知道将查询输入QSqlQuery的方式是否有问题?或者我可能不正确地尝试使用value(n)方法?
如果两者都不是这种情况我会打赌我在查询中使用了self.dbImage.id.toString()的错误参数,在这种情况下我明天就会问一个同事。 / p>
答案 0 :(得分:3)
要迭代结果集,通常使用while
循环:
while(query.next()){
// do whatever you need with query.value()
}
如果您只对第一行感兴趣,可以使用first()
再次使用while
循环:
while(query.first()){
// do whatever you need with query.value()
}
编辑:抱歉,误解了您的问题。现在我看到你可能忘了在某些字符串中添加一些空格:
"from measurements"
到
" from measurements "
#^ Here and here ^^
如果没有这些空格,您的查询将类似于
"...d = 3, 1, 0))) AS `Average SA`from measurementsWHERE image_id = ..."
当然这不是一个有效的查询。