Tutorial #75: Connect to MySQL database using Qt 5 framework

Hi everyone!

Just as any other cross platform framework Qt helps to access a database, create and open one or more database connections. Qt supports a list of databases thereby providing access to the API exposed by the underlying DBMS (Database Management System). Once connected, developers can query the database using the QSqlQuery class. It can be used to execute DML (data manipulation language) statements such as SELECT, INSERT etc as well as DDL (data definition language) statements such as CREATE TABLE.

In this tutorial, we will learn how to connect to a MySQL database using the Qt 5 framework. We will also write a simple query to obtain data from our existing table.

Pre-requisites: Qt Creator, MySQL database server, MinGW compiler (Win-x64)

Step 1: Create Qt project

Launch Qt creator and create a new console application project called TestMySQLExample. Choose the default Desktop kit.

Step 2: Add Qt code

Next, you need to make changes to your main.cpp file by adding the following code. Make sure the MySQL database on your machine is up and running.

main.cpp

#include <QCoreApplication>
#include <QApplication>
#include <QtSql/QSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
#include <QDebug>

bool createConnection();

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    if (!createConnection()){

        qDebug() << "Not connected!";
        return 1;
    }
    else{

        qDebug() << "Connected!";

        QSqlQuery query;
        query.exec("SELECT name FROM student");

        while (query.next()) {
            QString name = query.value(0).toString();
            qDebug() << "name:" << name;
        }

        return 0;
    }

    return app.exec();
}

bool createConnection(){
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("testdb");
    db.setUserName("root");
    db.setPassword("rootpassword");
    if (!db.open()) {
        qDebug() << "Database error occurred";
        return false;
    }
    return true;
}

Important: Before you compile and run the above file, you need to ensure that the libmysql.dll is present within the MySQL directory. Also check whether the path to the same has been added to your Environment Variables.

.pro file

QT       += core
QT       -= gui
QT       += webkit webkitwidgets
QT       += sql
TARGET = TestMySqlExample
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

Save all changes. Build and run the application. If no errors occur then you should see the data from your table being displayed in the console. 🙂

output

Reference: Connecting to databases in Qt

Karan Balkar About Karan Balkar
self proclaimed extraterrestrial fandroid, computer engineer, amateur gamer and die hard punk rock fan!

15 thoughts on “Tutorial #75: Connect to MySQL database using Qt 5 framework

  1. hello,
    first of all thank you for your work here !
    i am new at programming and Qt and i must build a database connection but the user should enter the true username,hostname,databasename and password.you are giving them as a String form here. how can i give them as a variable so that the user can give these values self over a userinterface dialog window or any qt frame.

    I thank you in advance

  2. Great post. Doesn’t the line below need a semicolon after student but before the “?

    query.exec(“SELECT name FROM student”);

  3. Hi Karan,

    I wanted to connect to my database running in RasPi using QT running in ubuntu. I tried with the above approach but couldn’t get it connected. Any idea what I might be missing here??????

    Any help is highly appreciated.

    Thanks.

      • I have installed mysql on Raspberry pi 2 and used and run queries using terminal and it is working fine. But Now I want to connect mysql database to QTcreator.
        I did all ur steps but it always go in if(!db.open())
        and says Database Error Occurred.

        Any help?

      • I want to link mysql with qtcreater on Raspberry pi 2.
        I did all your steps but it always run
        if(!dbopen()) and gives error opening database.

        can some one help me?

Leave a Reply

Your email address will not be published. Required fields are marked *