Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

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;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top