Various Question about QSqlDatabase
-
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:(
-
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().