Kona Wikia
Advertisement
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
Advertisement