@jsulm You were right. I finally understood what you meant by getting the db at any time. Thank you very much for your help!
This is my working code:
#include "f1_system.h"
#include <QtSql/qsqldatabase.h>
#include <QtSql/qsqlquery.h>
#include <QtSql/qsqlerror.h>
#include <QtSql/qsqldriver.h>
F1_System::F1_System(QWidget *parent)
: QMainWindow(parent)
{
ui.setupUi(this);
QSqlDatabase db = QSqlDatabase::addDatabase("QODBC", "dataB");
QString connectionString = "Driver={SQL Server};Server=DESKTOP-4K9MAS2\\SQLEXPRESS01;Database=Formula1_BD;Trusted_Connection=yes;";
db.setDatabaseName(connectionString);
connect(ui.loginPushButton, SIGNAL(clicked()), this, SLOT(validateLogin()));
}
F1_System::~F1_System() {
QSqlDatabase::database("dataB").close();
}
void F1_System::validateLogin() {
if (QSqlDatabase::database("dataB").open()) {
QString selectUser("SELECT Username FROM Users WHERE Username = '" + ui.usernameInputField->text() + "' AND Userpassword = '" + ui.passwordInputField->text() + "';");
QSqlQuery qry(selectUser, QSqlDatabase::database("dataB"));
if (qry.next())
ui.label->setText("Status: You are logged in!");
else
ui.label->setText("Status: Wrong credentials!\nTry again!");
}
else
ui.label->setText("Failed to connect to the database!");
}