Unsolved 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"); base.setHostName(""); base.setUserName(""); base.setPassword(""); base.setDatabaseName(""); if(!base.open(){ baseOpened=false;//boolean } else{ baseOpened=true;} base.close(); base = QSqlDatabase();
After that, when i need to retreive data I use this code
QSqlDatabase db = QSqlDatabase::database(); QSqlQuery query; if(db.isOpen()) { query.exec("SELECT * ..."); ... db.close(); }
the problem is that when i let the application open for longtime i get an error "too many open files"
-
Hi,
Why are you closing the connection each time ?
-
This post is deleted! -
@SGaist
I have many tables and I access them from differents classes.
I think thatQSqlDatabase 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 ? -
@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. -
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.