7
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?

Littlebitter
  • 671
  • 3
  • 10
  • 19

1 Answers1

17

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.

Amartel
  • 4,248
  • 2
  • 15
  • 21
  • Does Qt documentation or some other docs say about this somewhere? 'cos I searched but didn't find.. – Littlebitter Apr 09 '13 at 13:25
  • 3
    Binding values is not a Qt's thing - it's SQL thing. You can read about it here, for example: http://use-the-index-luke.com/sql/where-clause/bind-parameters . Quote: "Bind parameters cannot change the structure of an SQL statement. That means you cannot use bind parameters for table or column names." – Amartel Apr 09 '13 at 13:31