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.

    1. 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?
    2. 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().



  • ok, and to close the database, close the connection ?



  • Open the database in some main function (if not main() at all) and close it there too.



  • the way to close it is:
    db.close();
    db.removedatabase(...)
    ?



  • 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().


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.