#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?
You need to initialise your
QSqlQueryusing theQSqlQuery(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
QSqlQuerylater.With an
ABCconstructor taking an initialised DB (create the DB in main):Or