Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving row count from QSqlQuery, but got -1

I'm trying to get the row count of a QSqlQuery, the database driver is qsqlite

bool Database::runSQL(QSqlQueryModel *model, const QString & q)
{
    Q_ASSERT (model);

    model->setQuery(QSqlQuery(q, my_db));
    rowCount = model->query().size();
    return my_db.lastError().isValid();
}

The query here is a select query, but I still get -1;

If I use model->rowCount() I get only ones that got displayed, e.g 256, but select count(*) returns 120k results.

What's wrong about it?

like image 948
daisy Avatar asked Jun 08 '13 04:06

daisy


2 Answers

This row count code extract works for SQLite3 based tables as well as handles the "fetchMore" issue associated with certain SQLite versions.

QSqlQuery query( m_database );

query.prepare( QString( "SELECT * FROM MyDatabaseTable WHERE SampleNumber = ?;"));
query.addBindValue( _sample_number );

bool table_ok = query.exec();
if ( !table_ok )
{
    DATABASETHREAD_REPORT_ERROR( "Error from MyDataBaseTable", query.lastError() );
}
else
{
    //  only way to get a row count, size function does not work for SQLite3
    query.last();
    int row_count = query.at() + 1;
    qDebug() << "getNoteCounts = " << row_count;
}
like image 168
SportPilot Avatar answered Sep 24 '22 01:09

SportPilot


The documentation says:

Returns ... -1 if the size cannot be determined or if the database does not support reporting information about query sizes.

SQLite indeed does not support this.

Please note that caching 120k records is not very efficient (nobody will look at all those); you should somehow filter them to get the result down to a manageable size.

like image 5
CL. Avatar answered Sep 20 '22 01:09

CL.