1. 程式人生 > >SQLite獲取查詢結果數

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次修改

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));
}

結果:      為實際查詢到的記錄數目。