QSqlQuery准备好的语句-正确用法 [英] QSqlQuery prepared statements - proper usage

查看:544
本文介绍了QSqlQuery准备好的语句-正确用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试确定将适当的语句与QSqlQuery一起使用的正确方法.这些文档在这个主题上不是很具体.

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();
}

那么这个代码片段会在连接database中创建一个永久的准备好的语句吗?该准备好的语句在调用select()之间是否会持续存在,即在函数返回并处理QSqlQuery query时将其保存吗?

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?

还是应该在堆上创建QSqlQuery并一次又一次使用同一实例?

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

推荐答案

好吧,我们的想法是必须在堆上创建QSqlQuery,准备查询并对其执行以下操作:

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. 使用QSqlQuery::[next|first|last|...]
  4. 读取数据
  5. QSqlQuery::finish
  6. 冲洗并重复
  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;
}

这篇关于QSqlQuery准备好的语句-正确用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆