PDA

View Full Version : SQL connection closure problem.



cbarmpar
7th September 2008, 22:26
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.


#include "database.h"

#include <QtGui>
#include <QApplication>

int main(int argc, char *argv[])
{
QApplication a(argc, argv);
database w;
w.show();
return a.exec();
}




#ifndef DATABASE_H
#define DATABASE_H

#include <QtGui/QWidget>
#include <QtSql>
#include "ui_database.h"
class A {
public:
QString pinakas;
QString onoma;
QString kodikos;
};

class database : public QWidget
{
Q_OBJECT

public:
database(QWidget *parent = 0);
~database();


public slots:
void sindesou();
void aposindesou();

private:
Ui::databaseClass ui;
A ena;
QSqlDatabase db;

};

#endif // DATABASE_H

database.cpp:

#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)
: 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()) {
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
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()
{

}

mummy
8th September 2008, 09:42
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).



db = QSqlDatabase::addDatabase("QMYSQL");


bye