问题描述
我正在尝试确定将适当的语句与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:
-
QSqlQuery::bindValue(s)
-
QSqlQuery::exec
- 使用
QSqlQuery::[next|first|last|...]
读取数据 -
QSqlQuery::finish
- 冲洗并重复
QSqlQuery::bindValue(s)
QSqlQuery::exec
- read data with
QSqlQuery::[next|first|last|...]
QSqlQuery::finish
- 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准备好的语句-正确用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!