SQL connection closure problem.
What i am trying to do is to make a dialog where the user enters the data needed for a connection and finally makes the connection.
I have two buttons.
The first button should check whether a connection has already been made and if not start a new connection. If a connection has already been made then write a message saying connection already open.
The second button should disconnect the database.
The problem is that I cannot disconnect the database and that instead of checking whether one is already open it creates another one each time i ress the button. (and I receive the relevant error code form the command line).
I have attached the code. I cant figure out what's wrong on my own.Your help is much appreciated.
Many thanks in advance.
Code:
#include "database.h"
#include <QtGui>
#include <QApplication>
int main(int argc, char *argv[])
{
database w;
w.show();
return a.exec();
}
Code:
#ifndef DATABASE_H
#define DATABASE_H
#include <QtGui/QWidget>
#include <QtSql>
#include "ui_database.h"
class A {
public:
};
{
Q_OBJECT
public:
~database();
public slots:
void sindesou();
void aposindesou();
private:
Ui::databaseClass ui;
A ena;
};
#endif // DATABASE_H
database.cpp:
Code:
#include "database.h"
#include <QtSql>
#include <QMessageBox>
#include <QSqlDatabase>
#include <QSqlError>
#include <QSqlQuery>
#include <QApplication>
#include <QCoreApplication>
#include <QDebug>
#include "ui_database.h"
database
::database(QWidget *parent
){
ui.setupUi(this);
connect(ui.sindesi, SIGNAL(clicked()), this, SLOT(sindesou()));
connect(ui.aposindesi, SIGNAL(clicked()), this, SLOT(aposindesou()));
//QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
}
void database::sindesou() {
ena.pinakas = ui.pinakas->text();
ena.onoma = ui.onoma->text();
ena.kodikos = ui.kodikos->text();
if (!db.open()) {
db.setDatabaseName(ena.pinakas);
db.setUserName(ena.onoma);
db.setPassword(ena.kodikos);
db.setHostName("127.0.0.1");
db.setPort( 3306 );
if (!db.open()) {
ui.katastasi->setText("Not connected");
} else {
ui.katastasi->setText("connected");
}
}
else {
ui.katastasi->setText("It has already been connected");
}
};
void database::aposindesou() {
db.close();///<<--- This doesnt close the connection
}
database::~database()
{
}
Re: SQL connection closure problem.
Hello,
you create a local object of QDatabase in line 29 of database.cpp (sindesou) and open this local object.
In aposindesou you close the QDatabase object of the class databse. But this object isn't open. You can't close it.
Maybe you should use the class database object in line 29 of database.cpp (sindesou).
bye