0

I have data in a MySQL database which I want to put into a vector in order to do some math on it. It may be that this issue is not specific to QSqlTableModels but rather any QAbstractTableModel, but I'm not sure. Right now, I have

model->QSqlQueryModel::setQuery(q); //model is a QSqlTableModel, q gets 1 column of data
QVector<QVariant> var;
var.reserve(num_rows);
QVariant datum;
QModelIndex idx;
for (i=0; i<num_rows; ++i)
{
    idx = model->index(i,0,QModelIndex()); 
    datum = model->data(idx);
    var.push_back(datum);
}

Is there any way to improve on this, such as a lower-level copy operation I could use?

EDIT: Following the suggestion of beduin, I tried doing this without the QSqlTableModel but rather by simply iterating through the QSqlQuery. This resulted in significantly slower performance. A copy operation that took 380ms using the above method took 525ms iterating through QSqlQuery, for example, and there were similar differences with other queries.

Matt Phillips
  • 9,465
  • 8
  • 44
  • 75

1 Answers1

2

If you just want to put data retrieved from database in a vector maybe it's no need in using QSqlTableModel. You just can use QSqlQuery. Here is an example:

QSqlQuery dbQuery(dbConnection); // constructing QSqlQuery with given connection

dbQuery.setForwardOnly(true); // pretends to speed up executions on some databases
dbQuery.setMode(Q3SqlCursor::ReadOnly);    

bool result = dbQuery.exec(queryString); // executing given query
if (!result) {
  //error processing
}
while (dbQuery.next()) {
  // column - desired column number to retrieve value. Count starts from 0.
  var.push_back(dbQuery.value(column));  
}

Unfortunately, I am not aware of any way to do this without iterating through QSqlQuery result.

beduin
  • 7,943
  • 3
  • 27
  • 24
  • @Matt Philips: Please, comment here result of your comparison. I am curious to see it.)) – beduin Apr 26 '11 at 08:08
  • @Matt Phillips: It's sounds very interesting because QT documantations says that QSqlQueryModel (and then QSqlTableModel, too) is implemented on top of QSqlQuery. I've tried to find some possible optimizations to my previous solution. I hope to find something. I've reedited my post. If you want, you can rerun you test. – beduin Apr 26 '11 at 14:06
  • Yes that is interesting, my guess is that the QSqlTableModel does some kind of indexing on the database which facilitates subsequent access. Some of the extra time with your version comes from simply running the query, I think; with my version I use QSqlTableModel::setQuery. I will look more deeply into it tonight. – Matt Phillips Apr 26 '11 at 14:31