Search code examples
c++qtprepare

Qt QSqlQuery prepare and bindValue not working


I have a problem with prepare and bindValue :(

db.open();
QSqlQuery q;
    q.prepare("SELECT id_malade,nom,prenom FROM Malade WHERE nom LIKE %:p% OR prenom = %:f% ;");
    q.bindValue(":p",ui->lineEdit->text());
    q.bindValue(":f",ui->lineEdit->text());
    qDebug() << q.boundValue(0) << " " << q.boundValue(1);
    qDebug() << q.executedQuery().toStdString().c_str(); db.close();

output is:

QVariant(QString, "zit")   QVariant(QString, "zit") 
SELECT id_malade,nom,prenom FROM Malade WHERE nom LIKE %?% OR prenom = %?% ;

I tried to change :p and :f with ? and use int positions in bindValue but no luck. The query got executed with success so I couldn't fetch the exact error. I used prepare and bindValue a lot in my program and it works fine the problem is only on this class :/


Solution

  • instead of

    [...] nom LIKE %:p% OR prenom = %:f%

    your prepare statement should read

    [...] nom LIKE '%'||:p||'%' OR prenom = '%'||:f||'%'