PDA

View Full Version : QSqlDatabase driver problem



croscato
21st November 2008, 12:01
Hi all!

I have the following code:



#ifndef QMYSQLCONNECTION_H
#define QMYSQLCONNECTION_H

#include <QObject>
#include <QSqlDatabase>

class QMysqlConnection: public QObject, protected QSqlDatabase
{
Q_OBJECT

friend class QMysqlTable;

public:
QMysqlConnection(const QString& host, const QString& user, const QString&
password, const QString database, QObject* = 0);

bool isOpen(void) const;
void close(void);
};

#endif // QMYSQLCONNECTION_H




#include <QDebug>
#include <QSqlError>

#include "QMysqlConnection.h"

// Public functions
QMysqlConnection::QMysqlConnection(const QString& host, const QString& user,
const QString& password, const QString database, QObject* parent):
QObject(parent)
{
this->addDatabase("QMYSQL");

this->setHostName(host);
this->setUserName(user);
this->setPassword(password);
this->setDatabaseName(database);

this->open();

qDebug() << "Last connection error = " << this->lastError();
}

bool QMysqlConnection::isOpen(void) const
{
return QSqlDatabase::isOpen();
}

void QMysqlConnection::close(void)
{
QSqlDatabase::close();
}


This returns me the following error:
QSqlError(-1, "Driver not loaded", "Driver not loaded")

But if I change this code


this->addDatabase("QMYSQL");

this->setHostName(host);
this->setUserName(user);
this->setPassword(password);
this->setDatabaseName(database);

this->open();

to this code:


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

db.setHostName(host);
db.setUserName(user);
db.setPassword(password);
db.setDatabaseName(database);

db.open();


it works! Why this code works and the other code not?

caduel
21st November 2008, 13:37
addDatabase returns a QSqlDatabase object.
You'd have to assign it to *this.
(Your own object still has/is/uses a default-constructed (i.e. not initialized) QSqlDatabase.)

HTH

croscato
21st November 2008, 16:16
A used the following code and the problem was solved:



QMysqlConnection::QMysqlConnection(const QString& host, const QString& user, const QString& password, const QString database, QObject* parent):
QObject(parent), QSqlDatabase(QSqlDatabase::addDatabase("QMYSQL"))


Thanks...