Error Qt: QSqlQuery :: value: not positioned on a valid record

1

My problem is that when executing the following code:

void MainWindow::on_loginButton_clicked() {
  QString userName = ui->userLineEdit->text();
  QString userPassword = ui->passwordLineEdit->text();

  QSqlQuery q;
  q.exec("SELECT name FROM users.name WHERE name = 'javier'");

  QString nombre = q.value(0).toString();
  qDebug() << nombre;
}

I get the following error when I press the call loginButton :

QSqlQuery::value: not positioned on a valid record ""
    
asked by zuninool04 05.04.2018 в 20:01
source

1 answer

1

Your program has two errors:

The query is incorrect

As you have commented in the comments, it should be:

"SELECT name FROM users WHERE name = 'javier'"

The SELECT syntax is:

SELECT [COLUMNAS] FROM [TABLAS] WHERE [FILTROS]

Only column names can be in the fields [COLUMNAS] and [FILTROS] .

Query Iteration

Once you have executed the query you have to move through the different records returned. If you look at your code, to access the returned values you use:

QString nombre = q.value(0).toString();

Where q is own QSqlQuery , that is, the object on which you have executed the query ... Then, if the query returns 3 records ... How can we access each one? There is no such thing as q.value([REGISTRO],[COLUMNA]) , so ... how is it done?

In the answer that you have deleted, you say to use q.first() ... that would be a very customized solution. There is a more generic one that allows you to work with as many records as the application returns, and it is through the next() method:

QSqlQuery q;

if(! q.exec("SELECT name FROM users.name WHERE name = 'javier'") )
{
  qDebug() << "Error en la consulta: "
           << q.lastError().text();

  return;
}

while( q.next() )
{
  QString nombre = q.value(0).toString();
  // ...
}

If only a single record is of interest, you can change the while to if ... so you get a fairly homogeneous code independent of the number of results obtained.

By the way, note that it is advisable to check the return value of exec ... it will not be that the query could not be executed for some reason.

    
answered by 06.04.2018 в 07:44