Souad
Souad

Reputation: 161

Insertion into database in Qt

I'm trying to insert data into a table in a database, but the insertion failed. This is the error that I got:

[Oracle] [ODBC] [Ora]ORA-01008: not all variables bound.

here is my code:

#include <QtCore/QCoreApplication>

#include <QtSql>
#include<QtDebug>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

QSqlDatabase db= QSqlDatabase::addDatabase("QODBC");
db.setHostName("FCOESL200656336.qu.edu.qa");
db.setDatabaseName("EPQAS");
db.setUserName("SOUAD/testuser");
db.open();


if(db.open())
{
    qDebug() << "Opened!";

     QString sQuery =" insert into writers(W_Id,W_Name,Age,Gender,Nationality,Hand_Used)"
             "Values(:W_Id,:W_Name,:Age,:Gender,:Nationality,:Hand_Used)";

            QSqlQuery qry;

            qry.prepare(sQuery);

             qry.bindValue(":W_Id",3);
             qry.bindValue(":W_Name","fhsf");
             qry.bindValue(":Age",32);
             qry.bindValue(":Gender",'F');
             qry.bindValue(":Nationality","klfds");
             qry.bindValue(":Hand_Used",'R');

      if( !qry.exec(sQuery) )
          qDebug() << qry.lastError().text();
      else
        qDebug( "Inserted!" );
   }
else
{
    qDebug() <<"Connection failed" << db.lastError().text();
}

 db.close();
 return a.exec();

   }

How I can fix this problem?

Upvotes: 1

Views: 4164

Answers (1)

Blood
Blood

Reputation: 4186

You have a fail in your if statement.

if( !qry.exec(sQuery) )

Doing this, QSqlQuery is trying to execute sQuery, but in sQuery you didn't bind any values. You should do:

if( !qry.exec() )

because this function will execute query which you prepared earlier, with binded values. Whole should looks like this:

if(db.open())
{
    qDebug() << "Opened!";

     QSqlQuery qry;

     qry.prepare("INSERT INTO writers(W_Id,W_Name,Age,Gender,Nationality,Hand_Used)"
                 "VALUES(:W_Id,:W_Name,:Age,:Gender,:Nationality,:Hand_Used)");

     qry.bindValue(":W_Id",3);
     qry.bindValue(":W_Name","fhsf");
     qry.bindValue(":Age",32);
     qry.bindValue(":Gender",'F');
     qry.bindValue(":Nationality","klfds");
     qry.bindValue(":Hand_Used",'R');

     if( !qry.exec() )
         qDebug() << qry.lastError().text();
     else
         qDebug( "Inserted!" );
}

Upvotes: 4

Related Questions