SQLite获取查询结果数

示例代码

littleprinceviewer.h

class LittlePrinceViewer : public QWidget
{
private:
     QSqlQueryModel* model;
     QSqlDatabase*   db;

     Ui::LittlePrinceWidget* ui;
}

littleprinceviewer.cpp

void LittlePriceViewer::query(const QString &query)
{
     model->setQuery(query, *db);

     int count = model->rowCount();
     ui->label->setText(tr("%1 logs found.").arg(count));
}

结果: 当查询到的记录数>256,总是显示"256 logs found."
count = 记录数 if 记录数<=256;
count = 256     if 记录数>256.

第1次修改

Qt Assistant对函数int QSqlQueryModel::rowCount(const QModelIndex & parent = QModelIndex()) const的说明:
If the database supports returning the size of a query (see QSqlDriver::hasFeature()), the number of rows of the current query is returned. Otherwise, returns the number of rows currently cached on the client.
parent should always be an invalid QModelIndex.
This function was introduced in Qt 4.1.
See also canFetchMore() and QSqlDriver::hasFeature().
所以,int count = model->rowCount();语句获取到的是缓存的行数。
根据指引查看canFetchMore(), fetchMore()函数:
void QSqlQueryModel::fetchMore(const QModelIndex & parent = QModelIndex())
Fetches more rows from a database. This only affects databases that don't report back the size of a query (see QSqlDriver::hasFeature()).
To force fetching of the entire result set, you can use the following:
while (myModel->canFetchMore())
    myModel->fetchMore();


void LittlePriceViewer::query(const QString &query)
{
     model->setQuery(query, *db);

     int count = model->rowCount();
     if (model->canFetchMore())
     {
         model->fetchMore();
         count += model->rowCount();
     }
     ui->label->setText(tr("%1 logs found.").arg(count));
}


结果: 当查询到的记录数>767,总是显示"767 logs found."
count = 记录数 if 记录数<=767;
count = 767   if 记录数>767.

第2次修改

参考了http://stackoverflow.com/questions/3615636/select-count-in-sqlite
void LittlePriceViewer::query(const QString &query)
{
     QString str(query);
     str.replace(QRegExp("SELECT.+FROM"), "SELECT count(*) FROM");

     model->setQuery(str, *m_pDb);
     int count = model->record(0).value("count(*)").toInt(); 

     model->setQuery(query, *db);
     ui->label->setText(tr("%1 logs found.").arg(count));
}

结果:
     为实际查询到的记录数目。

你可能感兴趣的:(Qt)