Important: Please read the Qt Code of Conduct -

The correct way to open mysql connection

  • Hi,
    My Qt application need to connect to MySQL database to retrieve or add data.
    In my main class, I create the connection (only one time) using this code:

    QSqlDatabase base = QSqlDatabase::addDatabase("QMYSQL");
        else{        baseOpened=true;}
        base = QSqlDatabase();

    After that, when i need to retreive data I use this code

    QSqlDatabase db = QSqlDatabase::database();
        QSqlQuery query;
            query.exec("SELECT * ...");

    the problem is that when i let the application open for longtime i get an error "too many open files"

  • Lifetime Qt Champion


    Why are you closing the connection each time ?

  • Lifetime Qt Champion

    This post is deleted!

  • @SGaist
    I have many tables and I access them from differents classes.
    I think that

    QSqlDatabase db = QSqlDatabase::database();

    open the database connection created in my main class so I need to close it.
    I don't know if this is the right way to do this so can you tell me if i need to close the connection each time ?

  • Lifetime Qt Champion

    @madababi If you close the connection how then you want to access the database?
    Keep the connection open and close it if your application is terminating or you know that you don't need it anymore.

  • Lifetime Qt Champion

    No it doesn't open anything. It returns an object that represent a connection, in this case, the default connection since you don't pass any parameter.

    If you close it somewhere it will stay closed until you re-open it.

Log in to reply