0

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

throwaway2013
  • 440
  • 8
  • 19

1 Answers1

1

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.

Community
  • 1
  • 1
Jacob Robbins
  • 1,860
  • 14
  • 16
  • I tried to use something along the lines of `if (!db.isOpen()) {db.open();}` but it doesn't work...:( My connection will randomly drop but the if statement wont trigger db.open();, however if I just forget about the if statement and do db.open(); it works.. – throwaway2013 Jun 30 '13 at 19:05
  • How do you know the db connection is being dropped? Are you getting any error messages? – Jacob Robbins Jun 30 '13 at 22:07
  • When I click on this button it's supposed to populate my combobox from a table. It works when I click it initially and x amount of times if I don't stop in between. If i dont do anything for over 10 seconds, my combobox doesn't get populated. So now what i do is I run a timer that does `SELECT 1;` every 9 seconds to keep the connection from dropping – throwaway2013 Jul 01 '13 at 04:02