0

This code returns no records:

QString sql = QString("SELECT * FROM %1 WHERE dd_nomdest LIKE '%:machine';").arg(TABLE_NEW_ORDERS);

QSqlQuery query(_db);
if (!query.prepare(sql))
{
    qWarning() << ID << "Prepare query failed" << sql;
    qWarning() << ID << query.lastError();
    return false;
}

query.bindValue(":machine", machine);
qDebug() << query.boundValues();

while (query.next())
{
    // do stuff
}

prepare and exec return true. boundValues return an empty list. The machine variables contains the expected value. If I compose the SQL string using the QString placeholder (instead of binding values) the query works as expected.

Where is the error in my syntax?

Qt 6.2.0, Ubuntu 21.10, SQL Server.

Mark
  • 4,338
  • 7
  • 58
  • 120
  • 1
    you can't use placeholders with table name or colimn names# – nbk Apr 19 '22 at 15:51
  • @nbk are you sure it applies to my code? I'm binding a column value not name – Mark Apr 19 '22 at 15:52
  • can you post the exact and colplete error message – nbk Apr 19 '22 at 15:54
  • @nbk, there are no error messages. Please read the question. All the calls returns `true`. But the query does not work as expected (i.e. it finds nothing) while creating the same query without bindings returns the expected records. – Mark Apr 19 '22 at 15:55
  • So I guess there is something wrong in my binding syntax – Mark Apr 19 '22 at 15:56

1 Answers1

1

You have to place the placeholder for sql % in the bindvalue and so it replaces the whole string

QString sql = QString("SELECT * FROM %1 WHERE dd_nomdest LIKE :machine;").arg(TABLE_NEW_ORDERS);
...
query.bindValue(":machine", ("%" + machine))
nbk
  • 45,398
  • 8
  • 30
  • 47