Important: Please read the Qt Code of Conduct -

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");
    if (! 
      QMessageBox::critical(0, QObject::tr("Database Error"),
    QSqlQuery query("SELECT * FROM test");   
    int index=0;
    while ( 

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

    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,

  • 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 (
    qDebug() << query.value(fieldNo).toString; //fieldNo should be the position of the field in your select query counting from 0

Log in to reply