Reputation: 440
So I've heard that it's good programming when you close your database connection as soon as you don't need that connection and just re-open it when you do. So, I've been closing my connection whenever I don't need it, however I've noticed that it's slowed down my program significantly (it takes ~2 seconds per window to open). Any way to solve this?
I've defined QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
as a global, and just did db.open();
or db.close();
whenever I needed. In addition, if I just keep my connection open the whole time, my windows load instantly.
Edit: Reason why people say this is because connections could get dropped/disconnected midway through using your program and it could lead to unsaved data/big problems etc
Upvotes: 0
Views: 1051
Reputation: 1930
As others have commented, leave the db connection open. If you're worried about a connection being dropped, you can use QSqlDatabase::isOpen()
to test it before you try to execute a query.
Leaving the connection open makes even more sense if you're using prepared queries (QSqlQuery::prepare
). The prepared queries will be available as long as the connection is open.
EDIT
You can change the inactivity timeout for non-interactive sessions (see sysvar_wait_timeout). I'm no MySQL expert, but this might help.
Upvotes: 1