本文介绍了QSqlQuery with prepare和bindValue用于列名Sqlite的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

void updateDB(const int id, const QString& column, const QVariant& value) const 
 //*****
 //all stuff on open DB etc. 
QSqlQuery query;
query.prepare("UPDATE table SET  :column = :value WHERE id = :id ");
query.bindValue(":column", QVariant(column));   
query.bindValue(":value", value);
query.bindValue(":id", id);
query.exec();

不起作用。同时如果我重写查询到

Doesn't work. Meanwhile if I rewrite query to

query.exec("UPDATE table SET " + column + " = " + value.toString() + " WHERE id = " + QString::number(id));

它也工作,如果我删除:列占位符和写入查询列名称,我测试这个。所以似乎我不能使用bindValue和占位符列名,至少与Sqlite。但我没有发现在任何文档中提到这一点。

it works. It also works if I delete :column placeholder and write into the query column name, on which I'm testing this. So it seems that I can't use bindValue and placeholders to column names, at least with Sqlite. But I didn't find in any documentation mention of this.

所以没有办法对列名使用bindValue和占位符,或者我缺少一些东西?

So there is no way to use bindValue and placeholders to column names, or I'm missing something?

推荐答案

正确的代码如下:

query.prepare(QString("UPDATE table SET %1 = :value WHERE id = :id ").arg(column));
query.bindValue(":value", value);

您绑定值而不是字段名称。

You bind values, not fields names.

PS:在阅读整个问题之前回答。是的,你是对的 - 没有办法使用bindValues来绑定列,不仅对于sqlite,而且对于每个数据库。

P.S.: answered before reading whole question. Yes, you are right - there is no way to use bindValues to bind columns, not only for sqlite, but for each db.

这篇关于QSqlQuery with prepare和bindValue用于列名Sqlite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 16:10