【问题标题】:How to access parameters from other fuction C++?如何从另一个函数 C++ 访问参数?
【发布时间】:2020-10-23 19:56:00
【问题描述】:

问题是我在它的 C/C++ 接口中使用 PostgreSQL,并且我试图从同一个类中的其他函数访问参数,我想在这个公共方法中使用这个参数 W。 exec() 将字符串输入数据库。

首先,我将 all 用作对象,并且都是 public

Connection.cppwInsert 函数中。

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;
}

在注释行之间,我尝试直接传递变量并且它有效,但我试图这样做,因为 main(). 作为接收函数的参数。

在我的 main() 中,我要求提供这些字符串。

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

然后在 Connection.cpp 中。在函数 insert 中,我尝试将从 main 收到的值传递给 wInsert 中的 W.exec()。我试图将我的 int Connection::wInsert() 转换为 string Connection::wInsert(string name, string lastname) 但我收到一个错误,因为 PostgreSQL 需要将其设为 int 才能正常工作。

所以,我也寻找将 int 转换为字符串,但我认为这完全不同或使用 ma​​lloc 函数,但我不知道如何在这段代码。

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;
}

【问题讨论】:

  • 没有官方的C++接口。 connectionwork 是什么?
  • @molbdnilo Connection 是我的班级,work 用于创建事务对象。

标签: c# c++ c c++11 visual-c++


【解决方案1】:

试着看看这个。我认为您需要使用 $1,$2 并将参数绑定到您的预编译语句

How to prepare statements and bind parameters in Postgresql for C++

【讨论】:

    猜你喜欢
    • 2020-07-11
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多