How to do it…

Connecting to SQL Server in Qt is really simple:

  1. Open Qt Creator and create a new Qt Widgets Application project.
  2. Open your project file (.pro) and add the sql module to your project, like so:
QT += core gui sql
  1. Open 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:

  1. Open mainwindow.h and add the following headers below the QMainWindow header:
#include <QMainWindow>
#include <QtSql>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QDebug>
  1. Open mainwindow.cpp and insert the following code into 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");

  1. Start the SQL query once the database connection has been opened:
    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());
}
}
  1. Print out any error texts:
else {
qDebug() << query.lastError().text();
}
db.close();
}
else {
qDebug() << "Failed to connect to database.";
}
}
  1. Compile and run your project now and you should get something like this:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset