How to get Data from MySQL and set it in a Label?



  • Here i show my code

    It Does not work because it returns nothing and my Database is not empty.
    I got a message from Qt, it says

    QSqlQuery::value: not positioned on a valid record
    .

    #include "Wind0.h"
    #include "ui_Wind0.h"
    #include <QSqlTableModel>
    #include <QMessageBox>
    #include <QSqlError>
    #include <QSqlQuery>
    #include <QDebug>
    #include <QSqlRecord>
    
    Wind0::Wind0(QWidget *parent) :
        QDialog(parent),
        ui(new Ui::Wind0)
    {
        ui->setupUi(this);
    
        mDatabase = QSqlDatabase::addDatabase("QMYSQL");
        mDatabase.setHostName("localhost");
        mDatabase.setDatabaseName("BD1");
        mDatabase.setPort(3306);
        mDatabase.setUserName("root");
        mDatabase.open();
    }
    
    Wind0::~Wind0()
    {
        delete ui;
    }
    void Wind0::on_pushButton_clicked()
    {
        QSqlQuery query;
        QString aux;
        query.prepare("select Name from Teacher");
        aux = query.value(1).toString ;
        ui->label->setText(aux);
    }
    


  • I got the solution :) I added exec and first

    void Wind0::on_pushButton_clicked()
    {
        QSqlQuery query;
        QString aux;
        query.prepare("select Name from Teacher");
        query.exec();
        query.first();
        aux = query.value(0).toString ;
        ui->label->setText(aux);
       if(!query.isActive()) {
        QMessageBox::information(0,"Bad Query", "BAD Query. It's not active");
    }
    

    Like


Log in to reply
 

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