B
B
BadCats2020-04-24 12:23:53
Qt
BadCats, 2020-04-24 12:23:53

Qt SqlLite empty list after regular SELECT query on non-empty table?

There is a listening table - foods:
5ea2ae5b31350683691510.png
5ea2ae65e3d43783752973.png

void MainWindow:: createConnection()
{
    dbase =   QSqlDatabase::addDatabase("QSQLITE", "foods");
    dbase.setDatabaseName(databaseName + ".db");
    dbase.open();
    if (!dbase.open()) {
        msgBox.setText("Cant connect to database.Cant open datbase file.");
        msgBox.exec();
    }
    else
    {
        QSqlQuery  d(dbase);
        d.prepare("SELECT COUNT(*) FROM foods");
        d.exec();
        int rows ;
        if (d.next()) {
            rows= d.value(0).toInt();
        }

        d.prepare("SELECT * FROM foods");
        d.exec();
        int columns= d.record().count();
        ui->tableWidget->setColumnCount(columns);
        ui->tableWidget->  setRowCount(rows);
        for (int var = 0; var < columns; ++var)
        {
            ui->tableWidget->setHorizontalHeaderItem(var, new QTableWidgetItem(d.record().fieldName(var)));
        }
       if( d.prepare("SELECT name FROM foods"));
       {
        d.exec();
        QList<QVariant> V;
        if (d.next()) {
            V= d.value(0).toList();
        }
        for (int var = 0; var < rows; ++var)
        {
            ui->tableWidget->item(var,0)->setText(V.at(var).toString());
        }
}
    }
}


And, here's the part:
d.prepare("SELECT COUNT(*) FROM foods");
        d.exec();
        int rows ;
        if (d.next()) {
            rows= d.value(0).toInt();
        }

- returns the actual number of table rows,
but the list V - remains empty by 0 elements:
if( d.prepare("SELECT name FROM foods"));
       {
        d.exec();
        QList<QVariant> V;
        if (d.next()) {
            V= d.value(0).toList();
        }

Already tried to create a new query QSqlQuery - d1 and execute the query on it, but the result is the same.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
K
Kastuś, 2020-04-25
@Gytim

A list of values ​​is returned from the table,
the list must be looped through, the
next value is obtained through d.next
(I advise you to read about iterators)
and this option works because value only 1pc

d.prepare("SELECT COUNT(*) FROM foods");
        d.exec();
        int rows ;
        if (d.next()) {
            rows= d.value(0).toInt();
        }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question