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 viaQString::arg()
, and then use that as the format string in a secondQString::arg()
method called later. You have to deal with this on a case-by-case basis. If you intend to use the firstQString
result for a secondQString::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 aQString::arg()
later you will end up withQString("...%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 theQString::arg()
documentation how/whether this can be done, it might needQString("...\\%1...").arg(...)
orQString("...%%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.