Various Question about QSqlDatabase
-
wrote on 5 Mar 2011, 12:52 last edited by
Hi guys, i have various question about QSqlDatabase.
My application contains 5 different classes, and in those 2 the same database is used.
In each class there are 7-8 function, and in each function there a query is executed.- to access the database from the class i have to declare QSqlDatabase db; it in the .h, is it good or not? Is there a better way to share it across the function in the same class?
- How can i completely close the connection and the database? I couldn't do it, in each try i made a message like: duplicate connection and so on was trown when trying to open another istance in the second class!
This is my code right now:
bla.h
@
Class bla {
...
..
private:
QSqlDatabase db;
....
}
@bla.cpp
@
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName("Application");
if (!db.open()) {
QMessageBox msgBox;
msgBox.setText("Impossibile Aprire il DataBase!!");
msgBox.exec();
}
@
Destructor
@
bla::~bla() {
....
db.close();
}
@There must be something wrong:(
-
wrote on 5 Mar 2011, 14:50 last edited by
Your approach of using a member variable to hold your database is valid. For sharing the database across your classes, you can retreive the same database connection by giving it a name when you first create it (so do that only once!), and then retreiving the connection using QSqlDatabase::database().
-
wrote on 5 Mar 2011, 18:47 last edited by
ok, and to close the database, close the connection ?
-
wrote on 5 Mar 2011, 18:52 last edited by
Open the database in some main function (if not main() at all) and close it there too.
-
wrote on 6 Mar 2011, 00:46 last edited by
the way to close it is:
db.close();
db.removedatabase(...)
? -
wrote on 6 Mar 2011, 09:59 last edited by
Yes. But note that you should make sure that there are no queries using this database left in scope. See the documentation of QSqlDatabase::removeDatabase().
5/6