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



  • @

    #include <QtCore/QCoreApplication>
    #include <QtSql/QSqlDatabase>
    #include <QtSql>
    #include <QStringList>
    #include <QDebug>

    struct Student
    {
    QString id;
    QString name;
    QString sex;
    };

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

    QSqlDatabase db=QSqlDatabase::addDatabase("QODBC");
    
    
    QString dsn = QString::fromLocal8Bit("DRIVER={SQL SERVER};SERVER=127.0.0.1;DATABASE=mydb");
    db.setDatabaseName(dsn);
    db.setUserName("admin");
    db.setPassword("123456");
    if(db.open()) {
        qDebug()<<"OK!";
    }
    else{
        qDebug()<<"Error!";
    }
    
    
    QSqlQuery query(db);
    query.exec&#40;"select * from NewStudent"&#41;;
    
    QSqlError error=query.lastError();
    qDebug()<<error.number();
    
    if(!query.isValid()){
        qDebug()<<"Invalid!";
    }
    
    while(query.next()){
        Student student;
    
        student.id=query.value(0).toString();
        student.name=query.value(1).toString();
        student.sex=query.value(2).toString();
    
        qDebug()<<"ID: "<<student.id<<" Name: "<<student.name<<" Sex: "<<student.sex;
    }
    
    
    return a.exec&#40;&#41;;
    

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



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


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.