开发者

Can you get a column of (MySQL) data into a vector in Qt without iterating?

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.开发者_Go百科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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜