14

I'm trying select a field of my date base, the code is:

if (db.db().isOpen())
{
  qDebug() << "OK";
  QSqlQuery query("SELECT state FROM jobs WHERE jobId = '553'", db.db());
  qDebug() << query.value(0).toString();
}
else
  qDebug() << "No ok"; 

The query is correct because when I do qDebug() << query.size;, it returns 1.

but with qDebug() << query.value(0).toString();, it returns:

OK 
QSqlQuery::value: not positioned on a valid record
""

How can I fix it?

AAEM
  • 1,837
  • 2
  • 18
  • 26
Jjreina
  • 2,633
  • 6
  • 33
  • 54

1 Answers1

33

You should call query.first() before you can access returned data. additionally if your query returns more than one row, you should iterate via query.next().

Davita
  • 8,928
  • 14
  • 67
  • 119
  • im doing these two things, but still getting the same issue. whats the deal? – ldgorman Aug 15 '12 at 12:32
  • An example (and useful details) you'll find on the [Qt's QSqlQuery documentation](http://doc.qt.io/qt-5/qsqlquery.html#details). – Semjon Mössinger Sep 11 '18 at 08:07
  • Just as a call out, you do not need to call first() before calling next(), as the latter will position on the first record if necessary. @Igdorman you are probably passing an incorrect index to value(), presumably because you called record() before the query was active (e.g. before calling exec()). – MuchToLearn Sep 25 '19 at 19:16