SQLite獲取查詢結果數
阿新 • • 發佈:2018-12-23
示例程式碼
結果:當查詢到的記錄數>256,總是顯示"256 logs found." count = 記錄數 if 記錄數<=256; count = 256 if 記錄數>256.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)); }
第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.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));
}
結果: 為實際查詢到的記錄數目。