[Solved]Error while using 'bindValue' for my QSqlQuery
-
I have a simple query that goes like this:
QSqlQuery query(QSqlDatabase::database(name)); query.prepare("SELECT * FROM :table WHERE login=:login"); query.bindValue(":table", GVars::strDbTabel); query.bindValue(":login", GVars::strUserLogin); if (!query.exec()) { qWarning() << "Database error: " << query.lastError().text(); }
Running this said that there is an error on the query at the point where my
strDbTabel
value is.If instead I do not use bind value and I directly enter the name of my table then it seems to be working fine:
QSqlQuery query(QSqlDatabase::database(name)); query.prepare("SELECT * FROM userTable WHERE login=:login"); query.bindValue(":login", GVars::strUserLogin); if (!query.exec()) { qWarning() << "Database error: " << query.lastError().text(); }
I event tried using
QSqlQueryModel
:QSqlQueryModel model; model.setQuery(QString("SELECT * FROM %1 WHERE login=%2").arg(GVars::strDbTabel).arg(GVars::strUserLogin));
with even worse results
QSqlQuery::exec: database not open
even though my database is open.
Why can't I use
bindValue
to chose my table name? -
Hi, while you can do a lot of stuff with
bindvalue
you cannot use it for selecting a table name :-(It's a limitation in the SQL spec. for more on this, see for example: Stackoverflow question