Unsolved What is the purpose of the QSqlDatabase connection name?
-
QSqlDatabase implementation forces user to use addDatabase() to create a new connection and it requires a connection name (or default connection).
I'm wondering why it doesn't allow user to directly create a connection with its public constructor (without assigning a name to it). If user needs to manage multiple connections with names, it can be easily done with QMap<QString, QSqlDatabase>.I guess there's a good reason to integrate the name - connection mapping into the class, but I couldn't find it by myself. Can anyone explain?
Thanks.
-
Did you check the documentation?
http://doc.qt.io/qt-5/qsqldatabase.html#database
An application can use multiple connections which have different names.
You can get a specific connection by using its name:QSqlDatabase QSqlDatabase::database(const QString & connectionName = QLatin1String( defaultConnection ), bool open = true);
-
@jsulm Yes, I read the document multiple times.
My question is, why QSqlDatabase class **forces **us to manage multiple instance in one way. Why it doesn't simply allow to create objects using constructor and let us manage as I need.
For example, many applications create multiple QFile objects, but QFile class doesn't force us to add name to each of them.
-
Well, you still can use your own implementation (like QMap<QString, QSqlDatabase> in your original post). But is there really a need for such a custom implementation? In your example you still need a string identifier for each connection, why no just use what is already there?
-
Hi,
@sarai Yes QFile does: it's the file name. QSqlDatabase allows you to handle one or more database connections through multiple possible drivers at the same time in a easy to use fashion. The design avoids you to have to create a QSqlDatabase instance and setting it up again and again in each class/function of your application where you would like to run a query. That also means that you don't have to put your credentials everywhere in your application. That way, you can easily get the connection you need in a multi database setup.