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 ?
-
@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 ? -
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.