QSqlQuery with prepare and bindValue for column name Sqlite

戏子无情 提交于 2019-12-06 01:39:13

问题


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

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.

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


回答1:


Correct code here would be:

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

You bind values, not fields names.

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.



来源:https://stackoverflow.com/questions/15902859/qsqlquery-with-prepare-and-bindvalue-for-column-name-sqlite

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