Sunday, June 1, 2014

Qt Creator & Mysql

   To demonstrate mysql connectivity with Qt ,Let us create a desktop application in qt creator that will add some record to mysql.Design your screen as follows

meanwhile on your database create a table as

              CREATE TABLE QT_TEST
                PName VARCHAR(200),
                PCountry VARCHAR(100),
                PAddress VARCHAR(500)
Lets comeback to our Qt App,In our QT App the Name control is of type lineEdit while Address control is of type TextEdit as it can be multiliner.

Here is main controls

1) txtlnName: Name of Person
2) txtteAddress: Address of Person
3) listWidget: Single select Drop down list
4) pbSubmit:submiting user input
5) pbReset: reset user screen

into Mainwindow.cpp add following header

#include <QtSql>

now on submit button's click slot,  read user input like below

    QString Name =ui->txtlnName->text();
    QString Address =ui->txtteAddress->toPlainText();

    QListWidgetItem *sel_item = ui->listWidget->currentItem();
    QString Country= sel_item->text();

Now call a function that will save user input to mysql

bool InsertRecord(QString Name,QString Country,QString Address)
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");//Driver
    db.setDatabaseName("test");//database name
    db.setUserName("root");//user name

    bool ok =;

    QSqlQuery query;
    if (ok){
            query.prepare( "INSERT INTO QT_TEST (PName,PCountry,PAddress) VALUES ( :PName,:PCountry,:PAddress ) ");
            query.bindValue( ":PName", Name);
            query.bindValue( ":PCountry", Country);
            query.bindValue( ":PAddress", Address);QT += sql

            return true;
    return false;

Try Run your application and submit input.Now go to your mysql GUI or command prompt and run

            SELECT * FROM QT_TEST

You will see your record has been inserted into table.

Note: If you got error about  Qtsql header not found try adding  
                      QT += sql
           into project file file.

No comments:

Post a Comment