QSqlQuery with prepare and bindValue for column name Sqlite

Littlebitter picture Littlebitter · Apr 9, 2013 · Viewed 11.8k times · Source
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?

Answer

Amartel picture Amartel · Apr 9, 2013

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.