Search code examples
c++mysqlclassconnectionfriend-class

Access Mysql * connection variable from different c++ class


I wrote c++ class to connect to mysql database:

hpp file

#include <vector>
#include <string>

#include "mysql/mysql.h"

#ifndef _DATA
#define _DATA

class Database {

public:
    string host; 
    string user; 
    string pwd; 
    string db; 
    MYSQL * connection;
    MYSQL_RES *result;
    MYSQL_ROW row;

Database(const string & host,
         const string & user,
     const string & pwd,
     const string & db);

    int createMysqlConnection();
};
#endif

cpp file

#include "Database.hpp"

Database::Database(const string & host,
           const string & user,
           const string & pwd,
           const string & db) :
    mysqlHost(host),
    mysqlUser(user),
    mysqlPassword(pwd),
    mysqlDBName(db)
{}
int Database::createMysqlConnection(){
    MYSQL * connection;
    connection = mysql_init(NULL);
               if(!mysql_real_connect(connection, mysqlHost.c_str(), mysqlUser.c_str(),
               mysqlPassword.c_str(), mysqlDBName.c_str(),
               0, NULL, 0)){
    fprintf(stderr, "Connection to database failed: %s\n",
        mysql_error(connection));
    return EXIT_FAILURE;
    }
    cout << "connected to mysql" << endl;
    };

When I'm trying to access connection variable from the main function or from a different class I always get an error like variable 'connection is not declared in this scope. I tried to use friend classes or inheritance to point to connection variable but it didn't work. I think I'm doing something wrong in my syntax.

Here is an example of how I try to point to this variable from different class:

Class risk: public Database {
public:
vector<sting> parameter;
Datasabse.connection;
etc....
}

Solution

  • to solve this problem i had to define MYSQL connection in class constructor. here is a code sample:

    class1.hpp

    ***headers***
    class Flight { 
    
    public:
    
    Flight(MYSQL * connection);
    
    MYSQL * c;
    
    MYSQL_RES * res;
    
    etc...
    

    Class1.cpp

    ***headers***
    
    Flight::Flight (MYSQL* connection)
    
    {
    
    c = connection;
    
    };
    

    etc...

    main.cpp

    ***headers***
    
    int main (int argc, char *argv[]) {
    
    Database db(localhost, user, etc..);
    
    db.createMysqlConnection;
    
    Flight fl(db.connection);
    
    fl.GetIDs();
    
    etc...