In this recipe, we will learn how to connect to our SQL database using Qt's SQL module.
Connecting to SQL server in Qt is really simple:
.pro
) and add the SQL module to your project, like so:QT += core gui sql
mainwindow.ui
and drag seven label widgets, a combo box, and a checkbox to the canvas. Set the text properties of four of the labels to Name:
, Age:
, Gender:
, and Married:
. Then, set the objectName
properties of the rest to name
, age
, gender
, and married
. There is no need to set the object name for the previous four labels because they're for display purposes only:mainwindow.h
and add the following headers below the QMainWindow
header:#include <QMainWindow> #include <QtSql> #include <QSqlDatabase> #include <QSqlQuery> #include <QDebug>
mainwindow.cpp
and insert the following code to the class constructor:MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("127.0.0.1"); db.setUserName("yourusername"); db.setPassword("yourpassword"); db.setDatabaseName("databasename"); if (db.open()) { QSqlQuery query; if (query.exec("SELECT name, age, gender, married FROM employee")) { while (query.next()) { qDebug() << query.value(0) << query.value(1) << query.value(2) << query.value(3); ui->name->setText(query.value(0).toString()); ui->age->setText(query.value(1).toString()); ui->gender->setCurrentIndex(query.value(2).toInt()); ui->married->setChecked(query.value(3).toBool()); } } else { qDebug() << query.lastError().text(); } db.close(); } else { qDebug() << "Failed to connect to database."; } }
The previous example shows you how to connect to your SQL database using the QSqlDatabase
class derived from the SQL module. You won't be able to access any of the classes related to SQL without adding the module to your Qt project.
We must tell Qt which SQL architecture we are running by mentioning it when calling the addDatabase()
function. Options supported by Qt are QSQLITE, QMYSQL, QMYSQL3, QODBC, QODBC3, QPSQL, and QPSQL7
If you encounter an error message that says, QSqlDatabase: QMYSQL driver not loaded, then you should again check whether the DLL files are placed in the correct directory.
We can send our SQL statements to the database through the QSqlQuery
class, and wait for it to return the results, which usually are either the data you requested or error messages due to invalid statements.
If there is any data coming from the database server, it will all be stored in the QSqlQuery
class. All you need to do to retrieve this data is to do a while
loop on the QSqlQuery
class to check for all existing records, and retrieve them by calling the value()
function.
3.143.235.219