Search code examples
c++qtqt5qsqlquery

Execute a %LIKE% query in Qt


I want to execute a parameterized in qt using value binding.

This is the code:

QString name = "Foo";
query->prepare("SELECT Name, Surname FROM employee WHERE Surname LIKE %:surname%");
query->bindValue(":surname", name);

The problem is with the % character: it generates an error while executing the query, however i don't known how to use it with qt.


Solution

  • You do not have to use "%" in the prepare but concatenate the QString, on the other hand it is not necessary so far I have not needed to use a QSqlQuery pointer so I recommend not using it since it has a copy constructor.

    QSqlQuery query;
    QString name = "Foo";
    query.prepare("SELECT Name, Surname FROM employee WHERE Surname LIKE :surname");
    query.bindValue(":surname", QString("%%1%").arg(name));
    query.exec();
    while(query.next())
        qDebug()<< query.value(0) << query.value(1);