gpt4 book ai didi

postgresql - QSqlQueryModel 准备语句(使用 QSqlQuery)不工作

转载 作者:行者123 更新时间:2023-11-29 12:45:26 24 4
gpt4 key购买 nike

我在将 QSqlQueryModel 与准备好的语句一起使用时遇到问题。手动执行语句时一切正常,但将其绑定(bind)到模型时 - 它不会执行。另一方面,当我使用“静态”查询(通过 QString)设置模型时 - 模型执行并加载数据。我究竟做错了什么?

我像这样准备查询:

QSqlQuery query;
query.prepare(QString("SELECT \
kontrahentid \
, trim(format ('%s %s %s', kontrahentnazwafirmy, kontrahentnazwisko, kontrahentimie) ) as nazwa \
FROM kontrahent \
WHERE %1 ilike ? \
").arg(searchBy));
query.addBindValue(searchString);

它在这样查询时有效:

if (query.exec()) {
while (query.next()) {
qDebug() << "{" << query.value(0) << ", " << query.value(1) << "}";
}
}

在 postgres 日志中我有 prepare 语句,并在之后执行它。但是当它绑定(bind)到模型时它不起作用:

QSqlQueryModel* model = new QSqlQueryModel(this);
model->setQuery(query);
//model->setQuery("SELECT kontrahentid, trim(format ('%s %s %s', kontrahentnazwafirmy, kontrahentnazwisko, kontrahentimie) ) as nazwa FROM kontrahent");
if (model->lastError().isValid()) {
qDebug() << model->lastError();
return;
}

for (int i = 0; i < model->rowCount(); ++i) {
//int id = model.record(i).value("id").toInt();
//QString name = model.record(i).value("name").toString();
qDebug() << model->record(i).value(0) << model->record(i).value(1);
}

在 postgres 日志中我只有 prepare 语句,没有执行的迹象......但是当取消注释带有“静态”查询的行时(并注释掉上面的那个)它工作得很好......

我做错了什么?在将查询对象绑定(bind)到模型之前,我必须在查询对象上运行 execute() 吗?

最佳答案

do i have to run execute() on the query object before binding it to the model?

是的。 QSqlQueryModel::setQuery(const QSqlQuery & query) 的文档说:

Note that the query must be active and must not be isForwardOnly().

要使查询处于事件状态,它必须已被执行。 QSqlQuery 的文档说:

Successfully executed SQL statements set the query's state to active so that isActive() returns true. Otherwise the query's state is set to inactive. In either case, when executing a new SQL statement, the query is positioned on an invalid record. An active query must be navigated to a valid record (so that isValid() returns true) before values can be retrieved.

关于postgresql - QSqlQueryModel 准备语句(使用 QSqlQuery)不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25544806/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com