samedi 4 juillet 2020

How to access parameters from other fuction C++?

Well the problem is that I'm using PostgreSQL in it's C/C++ Interface and I'm trying to access parameters from other function in the same Class, I want to use this parameters in This public method W.exec() to enter the strings to an DB.

First of all I'm using all as objects and all are public.

Connection.cpp In the function wInsert.

int Connection::wInsert() {
  try {
    connection c(stringConnection);
    if (c.is_open()) {
      work W(c);
      int size = sql - > size();
      /*string name,lastname;
      cout << "Name";
      cin >> name;
      cout << "Last name";
      cin >> lastname;
      W.exec(this->insert(string name,string lastname));*/
      W.exec(this - > insert(name, lastname)); // here is where I call the function **insert**
      cout << "Opened database successfully:" << endl;
      W.commit();
    } else {
      cout << "Can't open database" << endl;
      return 1;
    }
    c.disconnect();
  } catch (const std::exception & e) {
    cerr << e.what() << std::endl;
    return 1;
  }
  return 0;
}

Between the comment lines I tried to pass the variables directly and it worked,but I'm trying to do this since the main(). as parameters that recieve a function.

In my main() I ask for these strings.

Database * db;
string name, lastname;
cout << "Name\n";
cin >> name;
cout << "Last name\n";
cin >> lastname;
bd - >insert(name, lastname);

Then in Connection.cpp. In the function insert Is where I try to pass this values that I received from the main to the W.exec() in wInsert. I tried to convert my int Connection::wInsert() to string Connection::wInsert(string name, string lastname) but I got an error because PostgreSQL need this to be int to work properly.

So, I also looked for convert an int to string but I think this totally different or use the malloc function but I'm no sure how to implement that in this code.

char * Connection::insert(string name, string lastname) {
  sql = new string("INSERT INTO person(name,lastname)"\
    "VALUES (\'" + name + "\', \'" + lastname + "\');");
  int size;
  size = sql - > size() + 1;
  char * query = new char[size];
  strcpy(query, sql - > c_str());
  return query;
}

Aucun commentaire:

Enregistrer un commentaire