How to do it…

Let's create a simple program that demonstrates basic SQL query commands by following these steps:

  1. We can use our previous project files, but there are a couple of things we need to change. Open mainwindow.ui and replace the labels for Name and Age with line-edit widgets. Then, add three buttons to the canvas and call them UPDATE, INSERT, and DELETE:

  1. Open mainwindow.h and add the following variables under the private inheritance:
private:
Ui::MainWindow *ui;
QSqlDatabase db;
bool connected;
int currentID;
  1. Open mainwindow.cpp and go to the class constructor. It is still pretty much the same as the previous example, except we store the database connection status in a Boolean variable called connected, and we also obtain the ID of the data from the database and store it to an integer variable called currentID:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent), ui(new Ui::MainWindow) {
ui->setupUi(this);
db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("127.0.0.1");
db.setUserName("yourusername");
db.setPassword("yourpassword");
db.setDatabaseName("databasename");
connected = db.open();

  1. Let's make a query after we have connected to the database:
if (connected) {
QSqlQuery query;
if (query.exec("SELECT id, name, age, gender, married FROM employee")) {
while (query.next()) {
currentID = query.value(0).toInt();
ui->name->setText(query.value(1).toString());
ui->age->setText(query.value(2).toString());
ui->gender->setCurrentIndex(query.value(3).toInt());
ui->married->setChecked(query.value(4).toBool());
}
}
  1. Print out any error messages:
   else {
qDebug() << query.lastError().text();
}
}
else {
qDebug() << "Failed to connect to database.";
}
}
  1. Go to mainwindow.ui and right-click on one of the buttons we added to the canvas in step 1. Select Go to slot… and click OK. Repeat these steps on the other button, and now you should see three slot functions being added to both your mainwindow.h and mainwindow.cpp:
private slots:
void on_updateButton_clicked();
void on_insertButton_clicked();
void on_deleteButton_clicked();
  1. Open mainwindow.cpp and we will declare what the program will do when we click on the Update button:
void MainWindow::on_updateButton_clicked() {
if (connected) {
if (currentID == 0) {
qDebug() << "Nothing to update.";
}
else {
QString id = QString::number(currentID);
QString name = ui->name->text();
QString age = ui->age->text();
QString gender = QString::number(ui->gender->currentIndex());
QString married = QString::number(ui->married->isChecked());
  1. Make an UPDATE query, like so:

qDebug() << "UPDATE employee SET name = '" + name + "', age = '" + age + "', gender = " + gender + ", married = " + married + " WHERE id = " + id;
QSqlQuery query;
if (query.exec("UPDATE employee SET name = '" + name + "', age = '" + age + "', gender = " + gender + ", married = " + married + " WHERE id = " + id)) {
qDebug() << "Update success.";
}
  1. Print out the last error message, if any:
   else {
qDebug() << query.lastError().text();
}
}
} else {
qDebug() << "Failed to connect to database.";
}
}
  1. Declare what will happen when the INSERT button is clicked:
void MainWindow::on_insertButton_clicked() {
if (connected) {
QString name = ui->name->text();
QString age = ui->age->text();
QString gender = QString::number(ui->gender->currentIndex());
QString married = QString::number(ui->married->isChecked());
qDebug() << "INSERT INTO employee (name, age, gender, married) VALUES ('" + name + "','" + age + "', " + gender + "," + married + ")";

  1. Make an INSERT query, like so:
        QSqlQuery query;
if (query.exec("INSERT INTO employee (name, age, gender, married) VALUES ('" + name + "','" + age + "', " + gender + "," + married + ")")) {
currentID = query.lastInsertId().toInt();
qDebug() << "Insert success.";
} else {
qDebug() << query.lastError().text();
}
} else {
qDebug() << "Failed to connect to database.";
}
}
  1. Declare what will happen when the Delete button is clicked:
void MainWindow::on_deleteButton_clicked() {
if (connected) {
if (currentID == 0) {
qDebug() << "Nothing to delete.";
} else {
QString id = QString::number(currentID);
qDebug() << "DELETE FROM employee WHERE id = " + id;
QSqlQuery query;
if (query.exec("DELETE FROM employee WHERE id = " + id)) {
currentID = 0;
qDebug() << "Delete success.";
} else {
qDebug() << query.lastError().text();
}
}
} else {
qDebug() << "Failed to connect to database.";
}
}
  1. Call QSqlDatabase::close() at the class destructor to properly terminate the SQL connection before exiting the program:
MainWindow::~MainWindow() {
db.close();
delete ui;
}

  1. Compile and run the program now and you should be able to select the default data from the database. Then, you can choose to update it or delete it from the database. You can also insert new data into the database by clicking the Insert button. You can use phpMyAdmin to check whether the data is being altered correctly:

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

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