lundi 23 mars 2015

Escape % (percent) in QSqlQuery::addBindValue() for LIKE

I use an SQLite database with Qt. I bind the values to the query instead of passing them in the query string. However, I can't figure out how to properly escape a % (percent) in the bound value itself.


For example, how do I change this code so that it outputs va%ue1, but not value1?



QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(":memory:");
db.open();
QSqlQuery q(db);
q.exec("CREATE TABLE test (field1)");
q.exec("INSERT INTO test VALUES (\"value1\")");
q.exec("INSERT INTO test VALUES (\"va%ue1\")");
q.prepare("SELECT field1 FROM test WHERE field1 LIKE ?");
q.addBindValue("va%%%");
q.exec();
while (q.next()) {
qDebug() << q.value(0);
}


Right now this outputs both:



QVariant(QString, "value1")
QVariant(QString, "va%ue1")


I also tried with q.addBindValue("va\\%%");, but it didn't output anything at all.


Aucun commentaire:

Enregistrer un commentaire