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?
We can read from the Qt documentation about
QSqlDatabase
: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 returnedQSqlDatabase
object. The database is open only when you callQSqlDatabase::open
. So when you add the database in different places that the database is used, allQSqlDatabase
objects that use the same connection name are changed. So you may have a lot of overhead if you use manyQSqlDatabase
objects with the same connection name.In different parts of your code you can use
QSqlDatabase::database
which returns the database connection calledconnectionName
. This way you can access theQSqlDatabase
instance in different parts where you have actually calledaddDatabase
once at the beginning.