QSqlQuery not binding
-
wrote on 11 Aug 2022, 07:15 last edited by Kevin470 8 Nov 2022, 07:17
Hello,
I am trying to execute a simple select query to an sqlite database with one argument that I want to bind.
I have a couple of databases that I will be working on.
This is my codeQString table_name = "variant_list"; QSqlQuery query(database); query.prepare("SELECT * FROM :table"); query.bindValue(":table", table_name); qInfo() << "My Query:" << query.lastQuery(); qInfo() << "My Query:" << query.result(); if(!query.exec()) { qDebug() << "Can't Execute Query!!"; qDebug() << database.lastError(); return false; } else { qDebug() << "Query executed Successfully!"; return true; }
qInfo() << "My Query:" << query.lastQuery();
prints"My Query: "SELECT * FROM :table"
qDebug() << database.lastError();
printsQSqlError("", "", "")
I tried all methods to bind values from "https://doc.qt.io/qt-5/qsqlquery.html#approaches-to-binding-values".
It looks like it isn't binding in any of those cases.
Where can I be doing it wrong?
Thanks. -
Hi,
Bind variables are not available for all query types nor for all elements of an SQL statement.
Typically, the table name cannot be a bind variable.
One of the base rule is that bind variables cannot change the structure of a query.
-
Hi,
Bind variables are not available for all query types nor for all elements of an SQL statement.
Typically, the table name cannot be a bind variable.
One of the base rule is that bind variables cannot change the structure of a query.
wrote on 11 Aug 2022, 07:41 last edited by@SGaist Thank you for answering.
Could you let me know the possibilities that are available to be able to bind variables?
I tried an INSERT query"INSERT INTO variant_list (variant_name,variant_type) VALUES (:variant_name,:variant_type)"
and it worked like a charm.
Does that mean the Column Names and values are allowed to be bound and any other element in the query like the Statement, the table name etc. won't bind? -
@SGaist Thank you for answering.
Could you let me know the possibilities that are available to be able to bind variables?
I tried an INSERT query"INSERT INTO variant_list (variant_name,variant_type) VALUES (:variant_name,:variant_type)"
and it worked like a charm.
Does that mean the Column Names and values are allowed to be bound and any other element in the query like the Statement, the table name etc. won't bind?wrote on 11 Aug 2022, 08:02 last edited by@Kevin470
Your query will work because it binds values. Basically, that is all you can do. Not only can you not bind table names, you also could not bind the column names in your query (INSERT INTO variant_list (:variant_column_name, :variant_column_type) VALUES ...
not allowed). -
@Kevin470
Your query will work because it binds values. Basically, that is all you can do. Not only can you not bind table names, you also could not bind the column names in your query (INSERT INTO variant_list (:variant_column_name, :variant_column_type) VALUES ...
not allowed).
1/5