Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

share DB connection on multiple forms



  • Hi, I'm still testing/lerning :)
    I wonder if is correct to create a new connection on each form, like
    QSqlDatabase db =QSqlDatabase::addDatabase("QMYSQL","XXXX");
    db.setHostName("");
    db.setPort();
    db.setDatabaseName((""));
    db.setUserName("");
    db.setPassword("");
    changing only the XXXX
    Thanks


  • Lifetime Qt Champion

    @saulos The question can be answered by simply reading the documentation: https://doc.qt.io/qt-5/qsqldatabase.html#details



  • @Christian-Ehrlicher thanks, but still don't understand what happen :
    I create the connection on MainWindow ( form1) to connect to table1 and it works, when from form1 I open form2 to connect to tabe2 the connection is telling me cant find table2.
    If i create a new connection on form2 it works.
    Debugging the project I noted that form2 is created before form1 , this lead me to think that somewhere QT has a creation order , is this correct ? if so can I change this ?
    I usually create a connection once and share it with all the form, but here looks different because the creation order change also it create the form before my expectation .
    Thanks ;)


  • Lifetime Qt Champion

    @saulos said in share DB connection on multiple forms:

    Debugging the project I noted that form2 is created before form1

    Without showing code or providing more information nobody can tell as nobody knows what form1/from2 are and how they are used.
    You could also create the connection before creating any forms (in main() for example), then the order in which your forms are created do not matter.



  • Thanks to all, I found the error.
    I create a new class and put all the connection on that so I create the connection once and share with all the forms.
    Also fixed the creation order , calling the creation of form 2 at the end of the creation of form1.
    :)


Log in to reply