Search one record in Database MySQL



  • Hello,

    I'm trying to create a small aplication for windows that when writing a particular number in a text filed, by clicking the push button it search for that ID in the database and displays the corresponding fields.

    So far what I found was the code below, which presents all the features of the database, but has no way to select only a field and shows the result of that search.

    @#include <QtGui>
    #include <QtSql>
    int main(int argc,char* argv[])
    {
    QApplication app(argc,argv);
    QTableWidget* table = new QTableWidget();
    table->setWindowTitle("Connect to Mysql Database Example");

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("192.168.11.3");
    db.setDatabaseName("menudb");
    db.setUserName("root");
    db.setPassword("test");
    if (!db.open()) 
    {
      QMessageBox::critical(0, QObject::tr("Database Error"),
       db.lastError().text());    
    }
    
    QSqlQuery query("SELECT * FROM test");   
    
    table->setColumnCount(query.record().count());
    table->setRowCount(query.size());
    
    int index=0;
    while (query.next()) 
    {      
    

    table->setItem(index,0,new QTableWidgetItem(query.value(0).toString()));
    table->setItem(index,1,new QTableWidgetItem(query.value(1).toString()));
    index++;
    }

    table->show();
    return app.exec();
    

    }@

    Please folks, does anyone can give me an idea how to do it. I do not want code done, I look a explanation or tutorial, etc... in order to develop my knowledge, OK.

    This application is a hobby, it's unprofessional and I'm not a programmer, but a curious who loves the QT development.

    Best Regards,
    Carlos



  • You can select only the field you want in your query like this:
    @
    SELECT field_name FROM table
    @

    Or you can retrieve the field you want from your code .

    @
    while (query.next())
    {
    qDebug() << query.value(fieldNo).toString; //fieldNo should be the position of the field in your select query counting from 0
    }@


Log in to reply
 

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