SQLite create table does not work when inserting variable into query
Solved
General and Desktop
-
I am attempting to insert a variable into a query using
QSqlQuery::prepare()
. The code is the following.QSqlQuery query; // value.at(2).toString() returns the ID of the profile as a QString QString profilePropTable = "profile_" + value.at(2).toString() + "_properties"; query.prepare("create table if not exists ? (name TEXT, type TEXT, display_item TEXT"); query.bindValue(0, profilePropTable); query.exec();
The error I get (using
query.lastError().text()
) is "Parameter count mismatch". I have also used named placeholders with the same error. -
You cannot use a placeholder and bind variable in place of the table name, only for binding values to columns.
Something like this:
QString strQuery = QString( "create table if not exists profile_%1_properties name TEXT, type TEXT, display_item TEXT" ).arg(value.at(2).toString()); query.exec(strQuery);
but only if you are 100% certain the value in value.at(2) cannot be subverted by the user (security risk).