Reputation: 494
I have C++ object-oriented application and I want to make my several different classes to have ability to send mysql queries to database and get results. I want to have single program-lifetime connection with database. Additionally: If connection timed out, then I program to still do it's work, but then some class tries to send query, it would get exception.
I read this page: MySQL Connector/C++ Developer Guide But there is only iterative example, not OOP.
Upvotes: 1
Views: 715
Reputation: 16172
There are two solutions here:
1) Make the DatabaseConnection
class, create an instance of it during the application startup and then pass into other objects, something like this:
main() {
DatabaseConnection* connection = new DatabaseConnection('connection.string');
Application* myapp = new Application(connection);
myapp->run();
...
}
So you just pass the connection
instance to other objects which need the database access.
2) Use a singleton. I don't like singletons, but in this case the connection
object may be needed by many parts of your application and it can be annoying to always pass it around explicitly.
With singleton you will initialize the connection on the app startup and then will get it from the singleton like this:
//application startup
DatabaseConnection* connection = DatabaseConnection::instance()->init('connection.string');
...
// get the connection when you need it
DatabaseConnection *connection = DatabaseConnection::instance();
connection->query('my query here');
...
Upvotes: 1