Hej, w Qt jestem początkujący i korzystam z tego poradnika:
https://www.youtube.com/watch?v=Qc9Smcr-huk&list=PLS1QulWo1RIZjrD_OLju84cUaUlLRe5jQ&index=8
Problem z kodem dotyczy tego filmu i dwóch następnych.
Oto co mam napisane:
plik nagłówkowy klasy okna:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtSql>
#include <QtDebug>
#include <QFileInfo>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_pushButton_clicked();
private:
Ui::MainWindow *ui;
QSqlDatabase mydb;
};
#endif // MAINWINDOW_H
źródło:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
mydb=QSqlDatabase::addDatabase("QSQLITE");
mydb.setDatabaseName("C:/database.db");
if(!mydb.open()){
ui->label->setText("Failed to open the database ( first time )");
}else{
ui->label->setText("connected...");
}
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
QString username, password;
username = ui->lineEdit_username->text();
password = ui->lineEdit_userpassword->text();
if(!mydb.open()){
qDebug()<<"Failed to open the database ( second time )\n";
return;
}
QSqlQuery qry;
if(qry.exec("select * from Users where Name='"+username+"' and passwd='"+password+"'")) {
int count = 0;
while(qry.next()){
++count;
}
if(count==1)
ui->label->setText("username and password is correct.");
if(count>1)
ui->label->setText("Duplicate username and password.");
if(count==0)
ui->label->setText("username and password is incorrect.");
}else {
qDebug()<<"Failed to open the database ( third time )\n";
return;
}
}
Oto wynik wykonania programu:
Jak widać, dwa razy sprawdzamy czy udało się otworzyć bazę danych, co ciekawe nie ukazuje się komunikat że nie udało się tego dokonać niezależnie od tego czy baza danych ( plik *.db ) jest czy jej nie ma w określonej lokalizacji.
Dopiero w momencie wysłania zapytania:
if(qry.exec("select * from Users where Name='"+username+"' and passwd='"+password+"'")) {
int count = 0;
while(qry.next()){
++count;
}
if(count==1)
ui->label->setText("username and password is correct.");
if(count>1)
ui->label->setText("Duplicate username and password.");
if(count==0)
ui->label->setText("username and password is incorrect.");
}else {
qDebug()<<"Failed to open the database ( third time )\n";
return;
}
spełnia się warunek else... Nie mam pojęcia co zawaliłem, robiłem dokładnie tak jak w poradniku. Bardzo będę wdzięczny za pomoc w znalezieniu przyczyny.
pozdrawiam serdecznie :).