Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

how to get a correct result QString with SQL example



  • i have a method, that help me to build SQL query with operator 'like' :

    QString likeClause(const QString& fieldName, const QString& text)
    {
    return QString("%1 like '\%%2\%'").arg(fieldName, text);
    }

    The problem is, that we have a '%' symbol before text. text might be absolutely anyone massive of symbols from keyboard. And when we have a text like "1asdasd" or "2kakaka", it provokes QString system to use this combination of characters "...%1asdasd..." in QString::arg system, if further this string will be used in other string with QString::arg's

    How to escape this string once and for all from the QString::arg?

    i am try also this one

    return QString(fieldName + " like '\%" + text + "\%'");

    but it work only in this function, in next strings with args, when i will use this string, it breaks down....



  • @Artem1
    Pardon?

    text might be absolutely anyone massive of symbols from keyboard

    Your simple quoting won't work as you might think if, say, the user types a literal % character. However, I'm not sure you are asking/care about this.

    but it work only in this function, in next strings with args, when i will use this string, it breaks down....

    That is your problem. You cannot

    How to escape this string once and for all from the QString::arg?

    Basically, you have to be very careful if you take the output from some QString method, such as produced via QString::arg(), and then use that as the format string in a second QString::arg() method called later. You have to deal with this on a case-by-case basis. If you intend to use the first QString result for a second QString::arg() in this way, you must make the first result suitable for how you wish to use it later.

    For example --- and only as an example --- say the original text input string from user contains %1. If you naively just put that in a string to use as a QString::arg() later you will end up with QString("...%1...").arg(...). If you think this through this is probably not at all what you want, and will go wrong. In this case, when you produced the first string you should have "escaped" the user's %1 such that it is no longer recognized as a substitute sequence. Unfortunately I do not see in the QString::arg() documentation how/whether this can be done, it might need QString("...\\%1...").arg(...) or QString("...%%1...").arg(...), if it's even doable given the lack of clarification in the docs.....

    See also https://doc.qt.io/qt-5/qstring.html#arg-14, which in part tries to deal with such an issue.



  • @JonB thanks!