Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top