Sqlite & QSqlDatabase problem
Hi
I've a question on sqlite and QSqlDatabase class.
I found the follow example to connect to sqlite db:
Quote:
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:
Quote:
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
Re: Sqlite & QSqlDatabase problem
The following code creates an invalid (empty) QSqlDatabase object:
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?
Code:
if (!db.open()) {
return true;
}
It seems not logical?! (IMHO return false; would be better ;) )
Bye
Re: Sqlite & QSqlDatabase problem
Ok
so if I create an instance of the QSqlDatabase() object:
Quote:
QSqlDatabase db = new QSqlDatabase();
then I can't assign the db driver:
Quote:
db->QSqlDatabase::addDatabase("QSQLITE");
but I must use it so:
Quote:
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
Quote:
if (!db.open()) {
return true;
}
it is wrong
Bye and thanks
Re: Sqlite & QSqlDatabase problem
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.
Re: Sqlite & QSqlDatabase problem
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:
Re: Sqlite & QSqlDatabase problem