Reputation: 14033
#include <QtGui>
#include <QtSql>
#include <QApplication>
class ABC {
public:
QSqlDatabase db;
QSqlQuery memberQuery;
ABC() {
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("test");
qDebug() << "Database open test : " << db.open();
}
void database() {
qDebug() << "Inside database method..." << endl;
QSqlQuery localQuery ;
qDebug() << "Using local Query : " << localQuery.exec("create table if not exists alu (ini int)");
localQuery.clear();
qDebug() << "Using memeber query object: " << memberQuery.exec("create table if not exists alu (ini int)");
memberQuery.clear();
}
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
ABC ob;
ob.database();
return a.exec();
}
Following result is found after executing this code.
Database open test : true
Inside database method...
Using local Query : true
QSqlQuery::exec: database not open
Using memeber query object: false
My question is why can't I use a member object QSqlQuery instead of a local one?
Upvotes: 0
Views: 1424
Reputation: 8157
You need to initialise your QSqlQuery
using the QSqlQuery(QSqlDatabase db)
constructor.
To do this you will need to use initialiser lists in the constructor and have already setup the DB connection, or use pointers to initialise the QSqlQuery
later.
With an ABC
constructor taking an initialised DB (create the DB in main):
ABC(QSqlDatabase _db) :
db(_db),
memberQuery(db)
{
Q_ASSERT(db.isOpen());
}
Or
class ABC
{
QSqlDatabase db;
QSqlQuery* memberQueryPtr;
public:
ABC() : db(QSqlDatabase::addDatabase("QSQLITE")),memberQueryPtr(0)
{
db.setDatabaseName("test");
if (!db.open())
return;
memberQueryPtr = new QSqlQuery(db);
}
~ABC()
{
delete memberQueryPtr; memberQueryPtr = 0;
}
// ...
};
Upvotes: 3