Search code examples
mysqlqtqsqlquery

How to fix synthax error with INSERT Query on Qt?


I'm trying to make an application where the user can access a data base and add rows into the same data base. The problem is that I have an sql query synthax error, even though I believe I wrote it right:

void FenPrincipale::boutonAjouter(){

requete.bindValue(":Nom",ajout_nom->text());
requete.bindValue(":Catégorie",liste_categories->currentText());
requete.bindValue(":Commentaires",ajout_description->toPlainText());;

qDebug() << liste_categories->currentText();
qDebug() << ajout_description->toPlainText();
qDebug() << ajout_nom->text();

requete.exec("INSERT INTO objets (Nom, Catégorie, Commentaires, Image)"
                " VALUES (:Nom, :Catégorie, :Commentaires, test )");

if(requete.exec()) {
   qDebug() << "Ok - requete";
    // Boucle qui permet de parcourir les enregistrements renvoyés par la requête
  while(requete.next()) {


            }//fin du while
}//fin du if

      else {
           qDebug() << "Echec de la requête : " << requete.lastError();
           }

}

and I have this error:

QSqlError("1064", "QMYSQL: Unable to execute query", "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ':Nom, :Catégorie, :Commentaires, test )' at line 1")

I've searched everywhere on the web, but I can't find a solution to this, I don't see where I did a synthax error...

Could you help me out with this please? Thanks !


Solution

  • You need to prepare the query and then add the values to it

    As you seem to have problems with the acccent, put it in backticks, or remove them completely.

    see manual

    requete.prepare("INSERT INTO objets (Nom, `Catégorie`, Commentaires, Image)"
                    " VALUES (:Nom, :Catégorie, :Commentaires, test )");
    requete.bindValue(":Nom",ajout_nom->text());
    requete.bindValue(":Catégorie",liste_categories->currentText());
    requete.bindValue(":Commentaires",ajout_description->toPlainText());
    requete.exec