1

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.

2
  • 1
    did you try tangentsoft.net/mysql++ ? Commented Feb 3, 2016 at 9:50
  • no, im reading ur link now. But still there is all examples how to create mysql connection in main() Commented Feb 3, 2016 at 9:52

1 Answer 1

1

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'); 
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.