Managing database and connection lifetime

506 views Asked by At

In Qt there are a few steps that need to be finish until a database access can be done.

The very first step is to add a database by connection name:

QSqlDatabase::addDatabase("QMYSQL", connectionName);

After this I can use open() and close() to open/close the corresponding connection.

That database can also be removed using the following call:

QSqlDatabase::removeDatabase(connectionName);

My application does this a lot since it accesses various databases in parallel processes for a lot of purposes. Also it is a server application that runs a very long time without being restarted.

It seems obvious to me that it is a bad idea to keep connections open all the time due possible network issues and limited connections on the server side.

However what about addDatabase()? Is there any harm or benefit in calling addDatabase() without calling removeDatabase() directly after (but on application exit only)? Or is it better to directly pair these calls at all times?

1

There are 1 answers

3
Nejat On BEST ANSWER

We can read from the Qt documentation about QSqlDatabase :

Warning: If you add a connection with the same name as an existing connection, the new connection replaces the old one. If you call this function more than once without specifying connectionName, the default connection will be the one replaced.

So when you add a database multiple times within a specific name or without specifying any (default connection), the connection is replaced and there is not to call removeDatabase.

But i think you should call QSqlDatabase::addDatabase() once when your application is started for each possible database and there is not need to add and then remove the connection each time you want to access it in different parts.

QSqlDatabase::addDatabase just assigns a connection name for the relevant SQL driver and the returned QSqlDatabase object. The database is open only when you call QSqlDatabase::open. So when you add the database in different places that the database is used, all QSqlDatabase objects that use the same connection name are changed. So you may have a lot of overhead if you use many QSqlDatabase objects with the same connection name.

In different parts of your code you can use QSqlDatabase::database which returns the database connection called connectionName. This way you can access the QSqlDatabase instance in different parts where you have actually called addDatabase once at the beginning.