May 7, 2012

DrizzleX DrizzleX
Lab Rat
2 posts

Could anyone tell me why I cant execute the SQL query?

 

  1. #include <QtCore/QCoreApplication>
  2. #include <QtSql/QSqlDatabase>
  3. #include <QtSql>
  4. #include <QStringList>
  5. #include <QDebug>
  6.  
  7. struct Student
  8. {
  9.     QString id;
  10.     QString name;
  11.     QString sex;
  12. };
  13.  
  14.  
  15. int main(int argc, char *argv[])
  16. {
  17.     QCoreApplication a(argc, argv);
  18.  
  19.     QSqlDatabase db=QSqlDatabase::addDatabase("QODBC");
  20.  
  21.  
  22.     QString dsn = QString::fromLocal8Bit("DRIVER={SQL SERVER};SERVER=127.0.0.1;DATABASE=mydb");
  23.     db.setDatabaseName(dsn);
  24.     db.setUserName("admin");
  25.     db.setPassword("123456");
  26.     if(db.open()) {
  27.         qDebug()<<"OK!";
  28.     }
  29.     else{
  30.         qDebug()<<"Error!";
  31.     }
  32.  
  33.  
  34.     QSqlQuery query(db);
  35.     query.exec("select * from NewStudent");
  36.  
  37.     QSqlError error=query.lastError();
  38.     qDebug()<<error.number();
  39.  
  40.     if(!query.isValid()){
  41.         qDebug()<<"Invalid!";
  42.     }
  43.  
  44.     while(query.next()){
  45.         Student student;
  46.  
  47.         student.id=query.value(0).toString();
  48.         student.name=query.value(1).toString();
  49.         student.sex=query.value(2).toString();
  50.  
  51.         qDebug()<<"ID: "<<student.id<<" Name: "<<student.name<<" Sex: "<<student.sex;
  52.     }
  53.  
  54.  
  55.     return a.exec();
  56. }

the output of qDebug()<<error.number();
is 16945,and Invalid is printed

1 reply

May 7, 2012

qxoz qxoz
Area 51 Engineer
585 posts

Where do you get the QODBC driver(how you build and from which source)?

 
  ‹‹ popup with toggle button      Layout questions (GraphicsView) ››

You must log in to post a reply. Not a member yet? Register here!