MYSQL * connection;
declares the connection variable as local to the constructor only. You must move it to the class definition in order to make it available somehow. Alternatively, make a connect
method in your Database object to explicitely create a new connection adlib. You will have to mirror it with a close method.
Yet another option is to create a dedicated class Connection
for connections, which would:
- be constructed with a
MYSQL *
,
- be created by the
connect
method of Database
as suggested above; the Database
class would act as a Connection
factory,
- sports all the necessary methods to handle it,
- and would call
mysql_close
in its destructor, to ensure proper termination of the underlying connection.
For instance:
class Connection {
protected:
MYSQL *connection;
public:
Connection(MYSQL *c): connection(c){}
virtual ~Connection() { mysql_close(connection); }
MYSQL_STMT * prepareQuery(const string &query) {
return mysql_prepare(connection, query.c_str(), query.length());
}
// other methods
};
The problem with this approach is that you quickly feel compeled to wrap all the API primitives with classes.