QSqlQuery prepared statements - proper usage

爷,独闯天下 提交于 2019-12-01 05:51:59

问题


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) {
    QSqlQuery query(database);
    query.prepare("SELECT * FROM theUniverse WHERE planet = :planet");
    query.bindValue(":planet", "earth");
    query.exec();
}

So will this snippet create a permanent prepared statement in the connection database? Will this prepared statement persist between calls to select(), i.e. will it be saved when the function returns and QSqlQuery query is disposed?

Or should I create QSqlQuery on the heap and use the same instance over and over again?


回答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 = new QSqlQuery(database);
            q->prepare(query);
            queries[query] = ret = q;
        } else {
            ret = queries[query];
        }
    }
    return ret;
}


来源:https://stackoverflow.com/questions/5609245/qsqlquery-prepared-statements-proper-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!