PDA

View Full Version : Sqlite & QSqlDatabase problem



rsimone
29th July 2009, 15:02
Hi
I've a question on sqlite and QSqlDatabase class.
I found the follow example to connect to sqlite db:



In example.cpp file
SqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
db.setHostName("localhost");
db.setDatabaseName("test.db");
if (!db.open()) {
return true;
}


it works but previously I had written the following code:



In example.h file
.......
QSqlDatabase *db;
......

In example.cpp file
b = new QSqlDatabase();
DriverList = db->drivers();
qDebug() << "Driver disponibili: ";
for (int i = 0; i < DriverList.size() ; ++i)
qDebug() << DriverList.at(i);
db->QSqlDatabase::addDatabase("QSQLITE");
db->setHostName("localhost");
db->setDatabaseName("test.db");
if (!db->open()) {
return true;
}



it compiles and it doesn't show any error by running but it don't open any connection to DB

Why???

p.s. sorry for my bad english

segi
29th July 2009, 15:27
The following code creates an invalid (empty) QSqlDatabase object:


QSqlDatabase* db = new QSqlDatabase();

To get a valid one you have to call QSqlDatabase::addDatabase.
Your second example calls this method in a wrong way. You ignore the returned object. So your QSqlDatabase object still be invalid.
In your first example it's right.

Btw: Do you want to use this code?


if (!db.open()) {
return true;
}

It seems not logical?! (IMHO return false; would be better ;) )

Bye

rsimone
29th July 2009, 15:59
Ok

so if I create an instance of the QSqlDatabase() object:


QSqlDatabase db = new QSqlDatabase();

then I can't assign the db driver:


db->QSqlDatabase::addDatabase("QSQLITE");

but I must use it so:


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

without creating first the QSqlDatabase object.

it seems me strange but maybe because I'm a java developer.

you are right



if (!db.open()) {
return true;
}

it is wrong

Bye and thanks

KhaoticMind
29th July 2009, 17:31
Nah, this is not stragen, even for a Java Dev. Its just that it QSqlDatabase is/behaves like a singleton (thou the constructor is public). So, you can create a new QSqlDatabase, but it is useless, since its not the one used by the class itself.

wysota
29th July 2009, 17:56
I'd even say that creating an object of this class on heap is an error. This is an explicitly shared class that should be assigned to an object allocated on stack. The database handler needs to be created using a static call to addDatabase() and thus calling db->addDatabase() is an error as well. The correct call is:

QSqlDatabase db = QSqlDatabase::addDatabase(...);

rsimone
29th July 2009, 21:52
thank you very much