trqa
trqa

Reputation: 25

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

this is the code I'm using to get the GoalsFor stat from this table after the user chooses a team from a ComboBox like this using this code:

 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();

}

But this is what the debugger always shows whenever I choose a team:

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

I tried everything I came across on the net and it seems like I'm doing exactly what other users or even the documentation say yet to no avail, any help would be appreciated, thanks !

Upvotes: 0

Views: 684

Answers (1)

ChrisMM
ChrisMM

Reputation: 10105

The problem seems to be with the SQL itself; since hteam isn't actually defined in SQL. I would instead recommend using the prepare function, which can also deal with filtering strings to prevent SQL injections. Something like the below should give you the result you are looking for.

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();
    }
  }
}

You were also grabbing indexOf("hometeam"), which isn't actually returned by the query. This then returns -1 which wouldn't be valid. Change this to "GoalsForH" to get the proper column index.

Upvotes: 1

Related Questions