Skip to content Skip to sidebar Skip to footer

Qsqlquery Prepared Statements - Proper Usage

I'm trying to determine the proper way to use prepared statements with QSqlQuery. The docs are not very specific on this subject. void select(const QSqlDatabase &database) {

Solution 1:

Ok, the idea is that you have to create QSqlQuery on heap, prepare the query and do the following with it:

  1. QSqlQuery::bindValue(s)
  2. QSqlQuery::exec
  3. read data with QSqlQuery::[next|first|last|...]
  4. QSqlQuery::finish
  5. rinse and repeat

the following snipped is useful to create, prepare and retrieve queries on heap:

QSqlDatabase database;
QMap<QString, QSqlQuery *> queries; //dont forget to delete them later!

QSqlQuery *prepareQuery(const QString &query)
{
    QSqlQuery *ret = 0;
        if (!queries.contains(query)) {
            QSqlQuery *q = newQSqlQuery(database);
            q->prepare(query);
            queries[query] = ret = q;
        } else {
            ret = queries[query];
        }
    }
    return ret;
}

Post a Comment for "Qsqlquery Prepared Statements - Proper Usage"