PDA

View Full Version : Using LIKE in parameterized SQL queries



MikeG
29th October 2009, 21:31
I cannot get LIKE to work in the following scenario (Like and Field are initialized, just using a snippet...):

QString Like; QString Field;
query.prepare("SELECT Name, CustomerID FROM Customer WHERE ? LIKE ?");
query.addBindValue(Field);
query.addBindValue(QString("%%1\%").arg(Like));
query.exec();

jiaco
30th October 2009, 06:49
Do you test the output of QString("%%1\%").arg(Like)? Why not use "\%%1\%" ?

MikeG
30th October 2009, 22:45
The output of
query.boundValue(1).toString() is the same for both "%%1\%" AND "\%%1\%". A blank string for "Like" reads "%%", a filled string reads "%text%" both without double-quotes. That's why it's confusing to me. When replacing the query's '?' with the bound values given directly to the database or fed unparameterized to query.exec(), it works fine.

If it matters, the database I'm using is MySQL, but I've had the same problem with SQLite, it's just that this instance matters much more than the other one.

jiaco
31st October 2009, 06:38
I cannot get LIKE to work in the following scenario (Like and Field are initialized, just using a snippet...):

QString Like; QString Field;
query.prepare("SELECT Name, CustomerID FROM Customer WHERE ? LIKE ?");
query.addBindValue(Field);
query.addBindValue(QString("%%1\%").arg(Like));
query.exec();

Well I just noticed something else, is the QString Like ever like set to the string "like"?

MikeG
2nd November 2009, 19:25
Like is set by user input in a QLineEdit, so it could be "like", "Like", "LIKE" or anything really. Setting QString Like to any variation of 'like' didn't do anything (none of the data would match to "like" either right now). Field is set through a QComboBox.